<style type="text/css">
    .nav-tabs-custom>.nav-tabs>li.active {
        border-top-color: #faa21c;
    }
</style>
<?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('financial_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>
    </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-balance-scale"></i> <?php echo $this->lang->line('Uniform_and_Inventory_Section'); ?></h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12">
                                <form id="reportForm" role="form" action="<?php echo site_url('admin/BIreports/uniform'); ?>" 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>
                                        </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($expenseList) && isset($feeList) && isset($incomeList)): ?>
    <div class="box bozero">
        <h3 class="titless pull-left"><i class="fa fa-money"></i> Trial Balance</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">Trial Balance</a>
                    </li>
                <?php endif; ?>
            </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>

                        <!-- Header Information -->
                        <div style="text-align: center; margin-bottom: 25px; width: 100%;">
                            <h2 style="font-size: 24px; margin-bottom: 5px;"><?php echo $settinglist[0]['name']; ?></h2>
                            <p style="font-size: 16px;"><?php echo $settinglist[0]['address']; ?></p>
                        </div>

                        <!-- Dates -->
                        <div style="margin-bottom: 25px; font-size: 16px; width: 100%;">
                            <div style="display: flex; justify-content: space-between;">
                                <?php if (isset($date_from2) || isset($date_to2)): ?>
                                    <p><strong>Date From:</strong> <?php echo isset($date_from2) ? date($this->customlib->getSchoolDateFormat(), strtotime($date_from2)) : ''; ?></p>
                                    <p><strong>Date To:</strong> <?php echo isset($date_to2) ? date($this->customlib->getSchoolDateFormat(), strtotime($date_to2)) : ''; ?></p>
                                <?php endif; ?>
                            </div>
                        </div>






                       <?php
// ------------------ Data Preparation Section ------------------
function fetchGL($name) {
    $ci = &get_instance();
    $row = $ci->db
        ->select('gl_code,name,account_type')
        ->from('glledger_account')
        ->where('LOWER(name)', strtolower($name))
        ->get()
        ->row();
    return $row ?: (object)['gl_code'=>'','name'=>$name,'account_type'=>''];
}

// Initialize totals and processed arrays
$fees_total = $customer_total = $discount_total = $fees_discount_total = $fine_total = $uniform_total = $sales_returns_total = $fees_returns_total = 0;

// Calculate fees total from fees summary
$processed_invoices = [];
$first_date = null;
foreach ($feeList as $invoice) {
    if (!isset($processed_invoices[$invoice['id']])) {
        $processed_invoices[$invoice['id']] = true;
        $fees_total += $invoice['invoice_amount'];
        if (!$first_date && isset($invoice['date'])) {
            $first_date = $invoice['date'];
        }
    }
}

// Fetch GL account details for 'Fees Income'
$feesRow = $this->db->select('*')->from('glledger_account')->where('id', '144')->get()->row();
$glcode_fees = $feesRow ? $feesRow->gl_code : '';
$name_fees   = $feesRow ? $feesRow->name    : 'Fees Income';

// Customer Sales + Discounts
foreach ($customerIncomeList as $ci) {
    $line = ($ci['quantity'] ?? 0) * ($ci['price'] ?? 0);
    $customer_total += $line;
    if (!empty($ci['discount'])) {
        $discount_total += ($ci['discount'] / 100) * $line;
    }
}

// Fee Discounts + Fines
foreach ($feediscount as $fd) {
    $fees_discount_total += $fd['amount_discount'] ?? 0;
    $fine_total         += $fd['amount_fine']     ?? 0;
}
$discount_total += $fees_discount_total;

// Uniform Sales
foreach ($uniformList as $u) {
    $uniform_total += ($u['quantity'] ?? 0) * ($u['amount'] ?? 0);
}

// Returns
foreach ($journalList as $j) {
    $book = strtolower(trim($j['cashbook']));
    if ($book === 'sales returns journal') {
        $sales_returns_total += $j['credit'];
    } elseif ($book === 'learner returns') {
        $fees_returns_total += $j['credit'];
    }
}

// GL Lookups for Income
$glSales       = fetchGL('Sales');
$glFees        = fetchGL('Fees Income');
$glUniform     = fetchGL('Sales Uniform');
$glSalesReturn = fetchGL('Sales Returns Journal');
$glFeeReturn   = fetchGL('Learner Returns');
$glDiscount    = fetchGL('Discounts');

// Build rows array
$rows = [];
if ($customer_total) {
    $rows[] = ['acct'=>$glSales->gl_code,'name'=>$glSales->name,'type'=>$glSales->account_type,'branch'=>'','debit'=>0,'credit'=>$customer_total];
}
if ($fees_total) {
    $rows[] = ['acct'=>$glFees->gl_code,'name'=>$glFees->name,'type'=>$glFees->account_type,'branch'=>'','debit'=>0,'credit'=>$fees_total];
}
if ($uniform_total) {
    $rows[] = ['acct'=>$glUniform->gl_code,'name'=>$glUniform->name,'type'=>$glUniform->account_type,'branch'=>'','debit'=>0,'credit'=>$uniform_total];
}
if ($fine_total) {
    $rows[] = ['acct'=>'','name'=>'Fine','type'=>'','branch'=>'','debit'=>0,'credit'=>$fine_total];
}
if ($sales_returns_total) {
    $rows[] = ['acct'=>'','name'=>'Sales Returns','type'=>'','branch'=>'','debit'=>$sales_returns_total,'credit'=>0];
}
if ($fees_returns_total) {
    $rows[] = ['acct'=>'','name'=>'Fees Returns','type'=>'','branch'=>'','debit'=>$fees_returns_total,'credit'=>0];
}
if ($discount_total) {
    $rows[] = ['acct'=>'','name'=>'Discounts','type'=>'','branch'=>'','debit'=>$discount_total,'credit'=>0];
}

// Cost of Sales & COGS
$total_COS = 0;
foreach ($cosList as $cos) {
    $total_COS += (float)$cos['amount'];
}
$total_Labor = $total_Materials = 0;
$this->db->where('Module','ST');
foreach ($this->db->get('supplier_invoice')->result_array() as $s) {
    $amt = ($s['price'] ?? 0) * ($s['quantity'] ?? 0);
    if (stripos($s['description'] ?? '', 'labor') !== false) {
        $total_Labor += $amt;
    } else {
        $total_Materials += $amt;
    }
}
$glCOS         = fetchGL('Purchases Grocery');
$glUniformCOGS = fetchGL('Purchases Uniform');

// Operating Expenses grouping — now pushed to **Credit** side
if (!empty($gl_expenseList) && is_array($gl_expenseList)) {
    $expense_accounts = [];
    foreach ($gl_expenseList as $e) {
        if ($e['module'] !== 'GL' || ((float)$e['debit'] + (float)$e['credit']) == 0) continue;
        $amt = max((float)$e['debit'], (float)$e['credit']);
        if (!empty($e['gl_name']) && strtolower($e['gl_account_type']) === 'expenses') {
            $key = $e['gl_code'].'_main';
            $disp_code = $e['gl_code'];
            $disp_name = $e['gl_name'];
        } elseif (!empty($e['sub_name']) && strtolower($e['parent_account_type']) === 'expenses') {
            $key = $e['glsub_code'].'_sub';
            $disp_code = $e['sub_account_type'].'>'.$e['glsub_code'];
            $disp_name = $e['sub_name'];
        } else {
            continue;
        }
        if (!isset($expense_accounts[$key])) {
            $expense_accounts[$key] = ['acct'=>$disp_code,'name'=>$disp_name,'type'=>'Expenses','branch'=>'','total'=>0];
        }
        $expense_accounts[$key]['total'] += $amt;
    }
    foreach ($expense_accounts as $acct) {
        // flip to credit side
        $rows[] = ['acct'=>$acct['acct'],'name'=>$acct['name'],'type'=>'Expenses','branch'=>'','debit'=>0,'credit'=>$acct['total']];
    }
}

// Other Income
$other_income = 0;
foreach ($journalList as $j) {
    if (!empty($j['description']) && stripos($j['description'], 'other income') !== false) {
        $other_income += (float)$j['debit'];
    }
}
$glOther = fetchGL('Other Income');
if ($other_income) {
    // moved Other Income to credit side
    $rows[] = ['acct'=>$glOther->gl_code,'name'=>$glOther->name,'type'=>$glOther->account_type,'branch'=>'','debit'=>0,'credit'=>$other_income];
}

                        // ------------------ Net Profit Calculation ------------------

                                
                              
                    
                                    // Calculate fees total from fees summary
                                    $fees_total = 0;
                                    $processed_invoices = [];
                                    $first_date = null;
                                    foreach ($feeList as $invoice) {
                                        if (!isset($processed_invoices[$invoice['id']])) {
                                            $processed_invoices[$invoice['id']] = true;
                                            $fees_total += $invoice['invoice_amount'];
                                            if (!$first_date && isset($invoice['date'])) {
                                                $first_date = $invoice['date'];
                                            }
                                        }
                                    }

                                    // Fetch GL account details for 'Fees Income'
                                    $this->db->select('*')
                                            ->from('glledger_account')
                                            ->where('id', '144');
                                    $queryFees = $this->db->get();
                                    $feesRow = $queryFees->row();
                                    $gl_code = $feesRow ? $feesRow->gl_code : 'N/A';
                                    $fees_name = $feesRow ? $feesRow->name : 'Fees Income';
                                    $gl_description = $feesRow ? $feesRow->description : '';

                                    // Sum up customer invoice totals and calculate discounts
                                    $customer_total = 0;
                                    $discount_total = 0;
                                    if (isset($customerIncomeList) && is_array($customerIncomeList)) {
                                        foreach ($customerIncomeList as $customer_invoice) {
                                            if (isset($customer_invoice['quantity']) && isset($customer_invoice['price'])) {
                                                $invoice_total = $customer_invoice['quantity'] * $customer_invoice['price'];
                                                if (isset($customer_invoice['discount'])) {
                                                    $discount_value = ($customer_invoice['discount'] / 100) * $invoice_total;
                                                    $discount_total += $discount_value;
                                                }
                                                $customer_total += $invoice_total;
                                            }
                                        }
                                    }

                                    // Calculate fee discounts and fines
                                    $fees_discount_total = 0;
                                    $fine_total = 0;
                                    if (isset($feediscount) && is_array($feediscount)) {
                                        foreach ($feediscount as $fee_discount) {
                                            if (isset($fee_discount['amount_discount'])) {
                                                $fees_discount_total += $fee_discount['amount_discount'];
                                            }
                                            if (isset($fee_discount['amount_fine'])) {
                                                $fine_total += $fee_discount['amount_fine'];
                                            }
                                        }
                                    }
                                    $discount_total += $fees_discount_total;

                                    // Calculate total Uniforms
                                    $uniform_total = 0;
                                    if (isset($uniformList) && is_array($uniformList)) {
                                        foreach ($uniformList as $uniform) {
                                            if (isset($uniform['quantity']) && isset($uniform['amount'])) {
                                                $uniform_total += $uniform['quantity'] * $uniform['amount'];
                                            }
                                        }
                                    }

                                    // Calculate total sales returns and fees returns
                                    $sales_returns_total = 0;
                                    $fees_returns_total = 0;
                                    if (isset($journalList) && is_array($journalList)) {
                                        foreach ($journalList as $journal) {
                                            if (isset($journal['credit'])) {
                                                $name = strtolower(trim($journal['cashbook']));
                                                if ($name === 'sales returns journal') {
                                                    $sales_returns_total += $journal['credit'];
                                                }
                                                if ($name === 'learner returns') {
                                                    $fees_returns_total += $journal['credit'];
                                                }
                                            }
                                        }
                                    }

                                    // Calculate total revenue: sales + fees + uniforms + fine minus all "less" items
                                    $total_revenue = ($customer_total + $fees_total + $uniform_total + $fine_total)
                                                    - ($sales_returns_total + $fees_returns_total + $discount_total);

                                    // Fetch GL account details for 'Sales'
                                    $this->db->select('*')
                                            ->from('glledger_account')
                                            ->where('id', '156');
                                    $querySales = $this->db->get();
                                    $salesRow = $querySales->row();
                                    $gl_sales_code = $salesRow ? $salesRow->gl_code : 'N/A';
                                    $sales_description = $salesRow ? $salesRow->description : 'Sales';

                                    // Fetch GL account details for 'Sales Uniform'
                                    $this->db->select('*')
                                            ->from('glledger_account')
                                            ->where('id', '146');
                                    $queryUniform = $this->db->get();
                                    $sales_uniform = $queryUniform->row();
                                    $uniform_gl_code = $sales_uniform ? $sales_uniform->gl_code : 'N/A';
                                    $uniform_gl_name = $sales_uniform ? $sales_uniform->name : 'Sales Uniform';
                                ?>

                               

                                
                                
                                <?php
                                    // Fetch the GL account for “purchases grocery” (case‐insensitive)
                                    $glAccount = $this->db
                                        ->select('gl_code, name, id')
                                        ->from('glledger_account')
                                        ->where('id', '152')
                                        ->get()
                                        ->row();

                                    $gl_code = $glAccount ? $glAccount->gl_code : 'N/A';
                                    $gl_name = $glAccount ? $glAccount->name    : 'Purchases Grocery';

                                    // Sum up all non‐zero COS amounts
                                    $total_COS = 0;
                                    foreach ($cosList as $cos) {
                                        $lineAmt = (float) $cos['amount'];
                                        if ($lineAmt == 0) {
                                            continue;
                                        }
                                        $total_COS += $lineAmt;
                                    }
                                ?>
                               <?php
                                // Initialize totals
                                $total_Materials = 0;
                                $total_Labor     = 0;

                                // Loop through the passed‐in supplierList (already filtered by date & Module)
                                if (!empty($supplierList)) {
                                    foreach ($supplierList as $supplier) {
                                        if (!empty($supplier['price']) && !empty($supplier['quantity'])) {
                                            $cogs_amount = $supplier['price'] * $supplier['quantity'];
                                            if ($cogs_amount > 0) {
                                                // “labor” in description → labor; otherwise materials
                                                if (!empty($supplier['description']) 
                                                    && stripos($supplier['description'], 'labor') !== false
                                                ) {
                                                    $total_Labor += $cogs_amount;
                                                } else {
                                                    $total_Materials += $cogs_amount;
                                                }
                                            }
                                        }
                                    }
                                }

                                // Fetch GL details for “Purchases Uniform” (same as before)
                                $this->db
                                    ->select('*')
                                    ->from('glledger_account')
                                    ->where('id', '148');
                                $queryUniform = $this->db->get();
                                $uniformRow   = $queryUniform->row();

                                $uniform_gl_code = $uniformRow 
                                    ? $uniformRow->gl_code 
                                    : 'N/A';
                                $uniform_gl_name = $uniformRow 
                                    ? $uniformRow->name 
                                    : 'Purchases Uniform';
                            ?>

                                

                                
                                <?php
                                    $total_COGS = $total_Materials + $total_Labor;
                                ?>
                               

                               <!-- Gross Profit -->
                                <?php
                                    // Gross Profit = Total Revenue - Total COS - Total COGS
                                    $gross_profit = $total_revenue - $total_COS - $total_COGS;
                                ?>
                                

                                <!-- Operating Expenses -->
                                
                                <?php
                                    $total_expense = 0;
                                    if (isset($gl_expenseList) && is_array($gl_expenseList)) {
                                        $expense_accounts = array();

                                        foreach ($gl_expenseList as $expense) {
                                            if ($expense['module'] !== 'GL' || (floatval($expense['debit']) + floatval($expense['credit']) == 0)) {
                                                continue;
                                            }

                                            $amount = max(floatval($expense['debit']), floatval($expense['credit']));

                                            if (!empty($expense['gl_name']) && strtolower($expense['gl_account_type']) === 'expenses') {
                                                // Main ledger expense
                                                $key = $expense['gl_code'] . "_main";
                                                $display_code = $expense['gl_code'];
                                                $display_name = $expense['gl_name'];

                                                if (!isset($expense_accounts[$key])) {
                                                    $expense_accounts[$key] = array(
                                                        'code'  => $display_code,
                                                        'name'  => $display_name,
                                                        'total' => 0
                                                    );
                                                }
                                                $expense_accounts[$key]['total'] += $amount;
                                            } elseif (!empty($expense['sub_name']) && strtolower($expense['parent_account_type']) === 'expenses') {
                                                // Sub-account with parent being an expense
                                                $key = $expense['glsub_code'] . "_sub";
                                                $display_code = $expense['sub_account_type'] . '>' . $expense['glsub_code'];
                                                $display_name = $expense['sub_name'];

                                                if (!isset($expense_accounts[$key])) {
                                                    $expense_accounts[$key] = array(
                                                        'code'  => $display_code,
                                                        'name'  => $display_name,
                                                        'total' => 0
                                                    );
                                                }
                                                $expense_accounts[$key]['total'] += $amount;
                                            }
                                        }

                                        foreach ($expense_accounts as $account) {
                                            $total_expense += $account['total'];
                                           
                                        }
                                    }
                                ?>
                                

                                <?php
                                    // Operating Profit = Gross Profit - Total Operating Expenses
                                    $operating_profit = $gross_profit - $total_expense;
                                ?>
                                <!-- Operating Profit Section -->
                                

                                <?php
                                    // Calculate total "Other Income" from the journal table
                                    $other_income_total = 0;
                                    if (isset($journalList) && is_array($journalList)) {
                                        foreach ($journalList as $journal) {
                                            if (isset($journal['debit']) && isset($journal['description'])) {
                                                $desc = strtolower(trim($journal['description']));
                                                if (strpos($desc, 'other income') !== false) {
                                                    $other_income_total += $journal['debit'];
                                                }
                                            }
                                        }
                                    }

                                    // Fetch the GL ledger account for "other income"
                                    $this->db->select('*')
                                             ->from('glledger_account')
                                             ->where('LOWER(account_type)', 'other income');
                                    $queryOther = $this->db->get();
                                    $otherRow = $queryOther->row();

                                    if ($otherRow) {
                                        $other_gl_code = $otherRow->gl_code;
                                        $other_gl_name = $otherRow->name;
                                    } else {
                                        $other_gl_code = 'N/A';
                                        $other_gl_name = 'other income';
                                    }
                                $net_profit = $operating_profit + $other_income_total;
                            
                                ?>
                                 
                        <?php
                        //-------------------------- Net Profit -------------------------
    // Sum existing debits and credits
    $sum_credit = array_sum(array_column($rows, 'credit'));
    $sum_debit  = array_sum(array_column($rows, 'debit')) + $total_COS + $total_Labor + $total_Materials;

    // Add Net Profit to debit side based on $net_profit
    $sum_debit += $net_profit;

    // Prepend Net Profit row
    $netRow = [
        'acct'   => 'Net Profit',
        'name'   => '',
        'type'   => '',
        'branch' => '',
        'debit'  => $net_profit,
        'credit' => 0
    ];
    array_unshift($rows, $netRow);
                        ?>

                        <table class="table table-bordered" style="width:100%; font-size:14px;">
                            <thead>
                                <tr>
                                    <th>Account Code</th>
                                    <th>Acc Name</th>
                                    <th>Account Type</th>
                                    <th></th>
                                    <th class="text-right">Debit</th>
                                    <th class="text-right">Credit</th>
                                </tr>
                            </thead>
                             

                        

                            
                        
                            
                                <tr style="font-weight:bold;"><td colspan="6">Income Statement</td></tr>
                                <?php foreach ($rows as $r): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($r['acct']) ?></td>
                                        <td><?= htmlspecialchars($r['name']) ?></td>
                                        <td><?= htmlspecialchars($r['type']) ?></td>
                                        <td><?= htmlspecialchars($r['branch']) ?></td>
                                        <td class="text-right"><?= $r['debit']  ? number_format($r['debit'],2)  : '' ?></td>
                                        <td class="text-right"><?= $r['credit'] ? number_format($r['credit'],2) : '' ?></td>
                                    </tr>
                                <?php endforeach; ?>

                                <?php if ($total_COS): ?>
                                    <tr>
                                        <td><?= $glCOS->gl_code ?></td>
                                        <td><?= htmlspecialchars($glCOS->name) ?></td>
                                        <td><?= $glCOS->account_type ?: 'Cost Of Sales' ?></td>
                                        <td></td>
                                        <td class="text-right"><?= number_format($total_COS,2) ?></td>
                                        <td></td>
                                    </tr>
                                <?php endif; ?>

                                <?php if ($total_Labor): ?>
                                    <tr>
                                        <td></td><td>Labor</td><td>Cost Of Sales</td><td></td>
                                        <td class="text-right"><?= number_format($total_Labor,2) ?></td><td></td>
                                    </tr>
                                <?php endif; ?>

                                <?php if ($total_Materials): ?>
                                    <tr>
                                        <td><?= $glUniformCOGS->gl_code ?></td>
                                        <td><?= htmlspecialchars($glUniformCOGS->name) ?></td>
                                        <td><?= $glUniformCOGS->account_type ?: 'Materials' ?></td>
                                        <td></td>
                                        <td class="text-right"><?= number_format($total_Materials,2) ?></td><td></td>
                                    </tr>
                                <?php endif; ?>

                                <tr style="font-weight:bold; border-top:2px solid #000; border-bottom:2px solid #000;">
                                    <td colspan="4">Totals</td>
                                    <td class="text-right"><?= number_format($sum_debit,2) ?></td>
                                    <td class="text-right"><?= number_format($sum_credit,2) ?></td>
                                </tr>
                        

                                <?php
                            
                                // Balance Sheet Section
                                // ---------------------

                                // Assume $net was calculated earlier in your Income Statement code:
                                if (!isset($net_profit) && isset($net_profit)) {
                                    $net_profit = $net_profit;
                                }

                                // Helper to fetch GL name and account type by GL code
                                function fetchGLByCode($code) {
                                    $ci = &get_instance();
                                    $row = $ci->db
                                        ->select('name, account_type')
                                        ->from('glledger_account')
                                        ->where('gl_code', $code)
                                        ->get()
                                        ->row();
                                    return $row ?: (object)['name' => '', 'account_type' => ''];
                                }

                                // Initialize running totals
                                $total_debit  = 0;
                                $total_credit = 0;

                                // Prepare an array of rows to render
                                $bs_rows = [];

                                // 1. Net Profit (at top, now on credit side)
                                if (isset($net_profit)) {
                                    // Credit net profit if positive, debit if loss
                                    $c = $net_profit > 0 ? $net_profit : 0;
                                    $d = $net_profit < 0 ? abs($net_profit) : 0;

                                    // Update totals
                                    $total_debit  += $d;
                                    $total_credit += $c;

                                    $bs_rows[] = [
                                        'acct'   => 'Net Profit',
                                        'name'   => '',
                                        'type'   => '',
                                        'branch' => '',
                                        'debit'  => $d,
                                        'credit' => $c,
                                    ];
                                }
                                // 1.1 Cash on Hand (after Net Profit)
                                // Calculate cash and grand total from gl_expenseList:
                                $cash = 0;
                                $grand_total = 0;

                                if (!empty($gl_expenseList) && is_array($gl_expenseList)) {
                                    foreach ($gl_expenseList as $entry) {
                                        $debit = isset($entry['debit']) ? (float) $entry['debit'] : 0;
                                        $credit = isset($entry['credit']) ? (float) $entry['credit'] : 0;
                                        $total = $debit - $credit;

                                        $cash += $total;
                                        $grand_total += $total;
                                    }
                                }

                                if ($cash != 0) {
                                    $total_debit += $cash;
                                    $bs_rows[] = [
                                        'acct'   => '',
                                        'name'   => 'Cash',
                                        'type'   => 'Current Asset',
                                        'branch' => '',
                                        'debit'  => $cash,
                                        'credit' => 0,
                                    ];
                                }

                                // 2. Accounts Receivable (lookup from GL ledger)
                                $processed      = [];
                                $fees_total     = 0;
                                foreach ($feeList as $inv) {
                                    if (!isset($processed[$inv['id']])) {
                                        $processed[$inv['id']] = true;
                                        $rate = $this->db
                                            ->select('foreign_rate')
                                            ->from('bank_rates')
                                            ->where('foreign_currency', $inv['payment_mode'] ?? '')
                                            ->get()
                                            ->row()
                                            ->foreign_rate ?? 1;
                                        $fees_total += $inv['invoice_amount'] / $rate;
                                    }
                                }
                                $customer_total = $discount_total = 0;
                                if (isset($customerIncomeList)) {
                                    foreach ($customerIncomeList as $ci) {
                                        $line             = ($ci['quantity'] ?? 0) * ($ci['price'] ?? 0);
                                        $discount_total  += ($ci['discount'] ?? 0) / 100 * $line;
                                        $customer_total  += $line;
                                    }
                                }
                                $fees_discount = $fine_total = 0;
                                if (isset($feediscount)) {
                                    foreach ($feediscount as $fd) {
                                        $fees_discount += $fd['amount_discount'] ?? 0;
                                        $fine_total    += $fd['amount_fine']     ?? 0;
                                    }
                                }
                                $uniform_total = 0;
                                if (isset($uniformList)) {
                                    foreach ($uniformList as $u) {
                                        $uniform_total += ($u['quantity'] ?? 0) * ($u['amount'] ?? 0);
                                    }
                                }
                                $sales_ret = $fees_ret = 0;
                                if (isset($journalList)) {
                                    foreach ($journalList as $j) {
                                        $n = strtolower(trim($j['cashbook']));
                                        if ($n === 'sales returns journal') $sales_ret += $j['credit'];
                                        if ($n === 'learner returns')       $fees_ret  += $j['credit'];
                                    }
                                }
                                $total_rev = ($customer_total + $fees_total + $uniform_total + $fine_total)
                                        - ($sales_ret + $fees_ret + $discount_total + $fees_discount);
                                if ($total_rev != 0) {
                                    $d = $total_rev > 0 ? $total_rev : 0;
                                    $c = $total_rev < 0 ? abs($total_rev) : 0;
                                    // Fetch GL details for Accounts Receivable
                                    $ci = &get_instance();
                                    $arRow = $ci->db
                                        ->select('gl_code, name, account_type')
                                        ->from('glledger_account')
                                        ->where('LOWER(name)', 'accounts receivable')
                                        ->get()
                                        ->row();
                                    $code = $arRow->gl_code ?? '';
                                    $name = $arRow->name ?? 'Accounts Receivable';
                                    $type = $arRow->account_type ?? '';
                                    $total_debit  += $d;
                                    $total_credit += $c;
                                    $bs_rows[] = [
                                        'acct'   => $code,
                                        'name'   => $name,
                                        'type'   => $type,
                                        'branch' => '',
                                        'debit'  => $d,
                                        'credit' => $c,
                                    ];
                                }

                                // 3. Inventory calculation and GL mapping with fallback to glsub_account
                                $total_materials = 0;
                                $total_labor     = 0;

                                // Fetch supplier invoices for module 'ST'
                                $invoices = $this->db
                                    ->where('Module', 'ST')
                                    ->get('supplier_invoice')
                                    ->result_array();

                                foreach ($invoices as $invoice) {
                                    $price    = $invoice['price'] ?? 0;
                                    $quantity = $invoice['quantity'] ?? 0;
                                    $amount   = $price * $quantity;

                                    if ($amount <= 0) {
                                        continue;
                                    }

                                    // Classify as labor if description contains 'labor', else material
                                    if (stripos($invoice['description'] ?? '', 'labor') !== false) {
                                        $total_labor += $amount;
                                    } else {
                                        $total_materials += $amount;
                                    }
                                }

                                $inventory = $total_materials + $total_labor;

                                if ($inventory > 0) {
                                    $total_debit += $inventory;

                                    // Normalize account name for lookup
                                    $lookupName = strtolower('uniform');
                                    $ci =& get_instance();

                                    // Try main ledger first
                                    $ledger = $ci->db
                                        ->select('gl_code AS code, name, account_type AS type')
                                        ->from('glledger_account')
                                        ->where('LOWER(name)', $lookupName)
                                        ->get()
                                        ->row();

                                    if ($ledger) {
                                        // Found directly in glledger_account
                                        $code = $ledger->code;
                                        $name = $ledger->name;
                                        $type = $ledger->type;
                                    } else {
                                        // Fallback to sub-account table
                                        $sub = $ci->db
                                            ->select('glsub_code, name, account_type AS parent_code')
                                            ->from('glsub_account')
                                            ->where('LOWER(name)', $lookupName)
                                            ->get()
                                            ->row();

                                        if ($sub) {
                                            // Lookup parent in glledger_account by the code stored in sub.account_type
                                            $parent = $ci->db
                                                ->select('account_type')
                                                ->from('glledger_account')
                                                ->where('gl_code', $sub->parent_code)
                                                ->get()
                                                ->row();

                                            // Build fields from sub-account
                                            $name = $sub->name;
                                            // Code is parent ledger code > sub-code
                                            $code = $sub->parent_code . '>' . $sub->glsub_code;
                                            // Use the parent's account_type if found
                                            $type = $parent->account_type ?? '';
                                        } else {
                                            // No match at all
                                            $code = '';
                                            $name = 'uniform';
                                            $type = '';
                                        }
                                    }

                                    $bs_rows[] = [
                                        'acct'   => $code,
                                        'name'   => $name,
                                        'type'   => $type,
                                        'branch' => '',
                                        'debit'  => $inventory,
                                        'credit' => 0,
                                    ];
                                }

                                // 4. Fixed Assets Section
                                $groups = [];
                                if (!empty($assetList) && is_array($assetList)) {
                                    // 1) Build flat groups keyed "main" or "main>sub"
                                    foreach ($assetList as $entry) {
                                        if (strtolower($entry['module']) !== 'gl') {
                                            continue;
                                        }

                                        if (!empty($entry['gl_name']) && strtolower($entry['gl_account_type']) === 'fixed assets') {
                                            $mainCode = $entry['gl_code'];
                                            $subCode  = '';
                                            $label    = $entry['gl_name'];
                                        } elseif (!empty($entry['sub_name']) && strtolower($entry['parent_account_type']) === 'fixed assets') {
                                            $mainCode = $entry['sub_account_type'];
                                            $subCode  = $entry['glsub_code'] ?? '';
                                            $label    = $entry['sub_name'];
                                        } else {
                                            continue;
                                        }

                                        $key = $mainCode . ($subCode !== '' ? '>' . $subCode : '');

                                        if (!isset($groups[$key])) {
                                            $groups[$key] = [
                                                'main'   => $mainCode,
                                                'label'  => $label,
                                                'debit'  => 0.0,
                                                'credit' => 0.0,
                                            ];
                                        }

                                        // only add positive values
                                        $groups[$key]['debit']  += max(0, floatval($entry['debit']));
                                        $groups[$key]['credit'] += max(0, floatval($entry['credit']));
                                    }

                                    // 2) Nest them by main code
                                    $nested = [];
                                    foreach ($groups as $key => $g) {
                                        $nested[$g['main']][$key] = $g;
                                    }
                                    ksort($nested, SORT_STRING);  // ensures main codes in order

                                    // 3) Emit rows: for each main, debit entries first, then credits
                                    foreach ($nested as $mainCode => $subs) {
                                        // sort subs by the full key ("main" or "main>sub")
                                        uksort($subs, 'strnatcmp');

                                        // a) all debits
                                        foreach ($subs as $code => $g) {
                                            if ($g['debit'] > 0) {
                                                $total_debit += $g['debit'];
                                                $bs_rows[] = [
                                                    'acct'   => $code,
                                                    'name'   => $g['label'],
                                                    'type'   => 'Fixed Assets',
                                                    'branch' => '',
                                                    'debit'  => $g['debit'],
                                                    'credit' => 0,
                                                ];
                                            }
                                        }

                                        // b) all credits
                                        foreach ($subs as $code => $g) {
                                            if ($g['credit'] > 0) {
                                                $total_credit += $g['credit'];
                                                $bs_rows[] = [
                                                    'acct'   => $code,
                                                    'name'   => $g['label'],
                                                    'type'   => 'Fixed Assets',
                                                    'branch' => '',
                                                    'debit'  => 0,
                                                    'credit' => $g['credit'],
                                                ];
                                            }
                                        }
                                    }
                                }

                                // 5. Accounts Payable (lookup from GL ledger)
                               $accounts_payable_total = 0;
                                if (!empty($supplierList) && is_array($supplierList)) {
                                    foreach ($supplierList as $sup) {
                                        $accounts_payable_total += (float)($sup['price'] ?? 0) * (float)($sup['quantity'] ?? 0);
                                    }
                                }

                                if ($accounts_payable_total > 0) {
                                    // Fetch GL details for Accounts Payable
                                    $ci = &get_instance();
                                    $apRow = $ci->db
                                        ->select('gl_code, name, account_type')
                                        ->from('glledger_account')
                                        ->where('LOWER(name)', 'accounts payable')
                                        ->get()
                                        ->row();
                                    $code = $apRow->gl_code ?? '';
                                    $name = $apRow->name ?? 'Accounts Payable';
                                    $type = $apRow->account_type ?? '';
                                    $total_credit += $accounts_payable_total;
                                    $bs_rows[] = [
                                        'acct'   => $code,
                                        'name'   => $name,
                                        'type'   => $type,
                                        'branch' => '',
                                        'debit'  => 0,
                                        'credit' => $accounts_payable_total,
                                    ];
                                }


                                // Render Balance Sheet rows
                                ?>
                                <tr style="font-weight:bold;"><td colspan="6">Balance Sheet</td></tr>
                                <?php foreach ($bs_rows as $r): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($r['acct']) ?></td>
                                        <td><?= htmlspecialchars($r['name']) ?></td>
                                        <td><?= htmlspecialchars($r['type']) ?></td>
                                        <td><?= htmlspecialchars($r['branch']) ?></td>
                                        <td class="text-right"><?= $r['debit']  ? number_format($r['debit'],2)  : '' ?></td>
                                        <td class="text-right"><?= $r['credit'] ? number_format($r['credit'],2) : '' ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr style="font-weight:bold;border-top:2px solid #000;border-bottom:2px solid #000;">
                                    <td colspan="4">Totals</td>
                                    <td class="text-right"><?= number_format($total_debit,2)  ?></td>
                                    <td class="text-right"><?= number_format($total_credit,2) ?></td>
                                </tr>



                            </tbody>
                        </table>

                        <div class="text-right" style="margin-top:20px;">
                            <button id="printStatementBtn" class="btn btn-info printInv"
                                    data-date_from="<?= $date_from2 ?>"
                                    data-date_to="<?= $date_to2 ?>"
                                    data-report_type="<?= $report_type ?>"
                                    title="Print Income Statement">
                                <i class="fa fa-print"></i> Print Trial Balance
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
<style>
    /* Apply hover effect to all table rows in the tbody */
    table tbody tr:hover {
        background-color: #d3d3d3 !important;
    }
</style>
<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/trialbalance/printtrialbalance") ?>',
                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>