<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('feescollectedvsuniformsalescollected'); ?></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/ipo'); ?>" 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($date_from2) && isset($date_to2)) { ?>
    <div class="box bozero">
        <h3 class="titless pull-left"><i class="fa fa-balance-scale"></i> Balance Sheet</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">Balance Sheet</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>

                        <!-- 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 
                                            if (isset($date_from2)) {
                                                echo date($this->customlib->getSchoolDateFormat(), strtotime($date_from2));
                                            }
                                        ?>
                                    </p>
                                    <p>
                                        <strong>Date To:</strong>
                                        <?php 
                                            if (isset($date_to2)) {
                                                echo date($this->customlib->getSchoolDateFormat(), strtotime($date_to2));
                                            }
                                        ?>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Income Statement Table -->
                        <table class="table table-bordered" style="width: 100%; font-size: 14px; border-collapse: collapse;">
                <!-- ASSETS -->
                <thead style="background-color:#f0f8ff; color:#fff;">
                    <tr><th colspan="3">Assets</th></tr>
                </thead>
                <tbody>
                    <!-- Current Assets -->
                    <tr style="background-color:#f0f8ff; font-weight:bold;">
                        <td colspan="3">Current Assets</td>
                    </tr>
                    <?php
                            // 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;

                                    // Optional: Still track "cash" value if you want to differentiate
                                    $cash += $total;

                                    $grand_total += $total;
                                }
                            }
                            ?>

                        <?php if ($grand_total > 0): ?>
                            <tr>
                                <td>Cash</td>
                                <td class="text-right"></td>
                                <td class="text-right">USD <?= number_format($grand_total, 2) ?></td>
                            </tr>
                        <?php endif; ?>

                         <?php 
                            // Calculate fees total from fees summary with currency conversion
                            $fees_total = 0;
                            $processed_invoices = [];
                            $first_date = null;
                            foreach ($feeList as $invoice) {
                                if (!isset($processed_invoices[$invoice['id']])) {
                                    $processed_invoices[$invoice['id']] = true;

                                    // original invoice amount & payment mode
                                    $original_amount = $invoice['invoice_amount'];
                                    $payment_mode    = $invoice['payment_mode'] ?? '';

                                    // lookup the foreign rate (default to 1)
                                    $query_rate = $this->db
                                        ->select('foreign_rate')
                                        ->from('bank_rates')
                                        ->where('foreign_currency', $payment_mode)
                                        ->get();
                                    $foreign_rate = $query_rate->row()->foreign_rate ?? 1;

                                    // convert any currency to USD
                                    $converted_amount = $original_amount / $foreign_rate;

                                    // accumulate converted amount
                                    $fees_total += $converted_amount;

                                    // capture first date
                                    if (!$first_date && !empty($invoice['date'])) {
                                        $first_date = $invoice['date'];
                                    }
                                }
                            }

                            // 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'], $customer_invoice['price'])) {
                                        $invoice_total = $customer_invoice['quantity'] * $customer_invoice['price'];
                                        if (isset($customer_invoice['discount'])) {
                                            $discount_total += ($customer_invoice['discount'] / 100) * $invoice_total;
                                        }
                                        $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) {
                                    $fees_discount_total += $fee_discount['amount_discount'] ?? 0;
                                    $fine_total          += $fee_discount['amount_fine']     ?? 0;
                                }
                            }
                            $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'], $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'], $journal['cashbook'])) {
                                        $name = strtolower(trim($journal['cashbook']));
                                        if ($name === 'sales returns journal') {
                                            $sales_returns_total += $journal['credit'];
                                        }
                                        if ($name === 'learner returns') {
                                            $fees_returns_total += $journal['credit'];
                                        }
                                    }
                                }
                            }

                            // Final Total Revenue
                            $total_revenue = ($customer_total + $fees_total + $uniform_total + $fine_total)
                                        - ($sales_returns_total + $fees_returns_total + $discount_total);

                            // Assign to Accounts Receivable
                            $accounts_receivable = $total_revenue;
                        ?>

                        <!-- Output Accounts Receivable as one line, only if non‐zero -->
                        <?php if ($accounts_receivable != 0): ?>
                            <tr>
                                <td>Accounts receivable</td>
                                <td class="text-right"></td>
                                <td class="text-right">USD <?= number_format($accounts_receivable, 2) ?></td>
                            </tr>
                        <?php endif; ?>


                                                            <?php
                                    // Initialize variables for total sums
                                    $total_Materials = 0;
                                    $total_Labor = 0;

                                    // Query the supplier_invoice table for records where Module = 'ST'
                                    $this->db->where('Module', 'ST');
                                    $query = $this->db->get('supplier_invoice');
                                    $supplierLists = $query->result_array();

                                    if (!empty($supplierList)) {
                                        foreach ($supplierList as $supplier) {
                                            if (isset($supplier['price']) && isset($supplier['quantity'])) {
                                                $cogs_amount = $supplier['price'] * $supplier['quantity'];
                                                if ($cogs_amount > 0) {
                                                    if (isset($supplier['description']) && stripos($supplier['description'], 'labor') !== false) {
                                                        $total_Labor += $cogs_amount;
                                                    } else {
                                                        $total_Materials += $cogs_amount;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // Calculate inventory
                                    $inventory = $total_Materials + $total_Labor;
                                    ?>
                                    <?php if ($inventory > 0): ?>
                                    <tr>
                                        <td>Inventory</td>
                                        <td class="text-right"></td>
                                        <td class="text-right">USD <?= number_format($inventory, 2) ?></td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php if ($prepaid_expenses > 0): ?>
                                        <tr>
                                            <td>Prepaid expenses</td>
                                            <td class="text-right"></td>
                                            <td class="text-right">USD <?= number_format($prepaid_expenses,2) ?></td>
                                </tr>
                                <?php endif; ?>

                                <?php if ($short_term_investments > 0): ?>
                                <tr>
                                    <td>Short‑term investments</td>
                                    <td class="text-right"></td>
                                    <td class="text-right">USD<?= number_format($short_term_investments,2) ?></td>
                                </tr>
                                <?php endif; ?>
                                <?php
                                    // Calculate total current assets by summing all non‐zero asset values
                                    $total_current_assets = 0;
                                    if ($grand_total > 0) {
                                        $total_current_assets += $grand_total;
                                    }
                                    if (!empty($accounts_receivable) && $accounts_receivable > 0) {
                                        $total_current_assets += $accounts_receivable;
                                    }
                                    if (!empty($inventory) && $inventory > 0) {
                                        $total_current_assets += $inventory;
                                    }
                                    if (!empty($prepaid_expenses) && $prepaid_expenses > 0) {
                                        $total_current_assets += $prepaid_expenses;
                                    }
                                    if (!empty($short_term_investments) && $short_term_investments > 0) {
                                        $total_current_assets += $short_term_investments;
                                    }
                                    ?>

                                    <tr style="font-weight:bold;">
                                        <td>Total current assets</td>
                                        <td class="text-right"></td>
                                        <td class="text-right">USD <?= number_format($total_current_assets, 2) ?></td>
                                    </tr>

                                    <!-- Fixed Assets -->
                        
                                    <tr style="background-color:#f0f8ff; font-weight:bold;">
                                        <td colspan="3">Fixed (Long-Term) Assets</td>
                                    </tr>
                                    <?php
                                    // Fixed Assets Section
                                    $netBookValues = [];
                                    $groups = [];

                                    if (!empty($assetList) && is_array($assetList)) {
                                        // Group entries by code
                                        foreach ($assetList as $entry) {
                                            if (strtolower($entry['module']) !== 'gl') continue;
                                            $debit  = floatval($entry['debit']);
                                            $credit = floatval($entry['credit']);
                                            $label  = null;
                                            $code   = null;

                                            if (!empty($entry['glid']) && strtolower($entry['gl_account_type']) === 'fixed assets') {
                                                $label = $entry['gl_name'];
                                                $code  = $entry['gl_code'];
                                            } elseif (!empty($entry['sub_name']) && strtolower($entry['parent_account_type']) === 'fixed assets') {
                                                $label = $entry['sub_name'];
                                                $code  = $entry['sub_account_type'];
                                            }
                                            if ($label === null || $code === null) continue;

                                            $groups[$code][] = ['label' => $label, 'debit' => $debit, 'credit' => $credit];
                                        }

                                        // Process each asset code group
                                        foreach ($groups as $code => $rows) {
                                            // Aggregate by label
                                            $debitByLabel  = [];
                                            $creditByLabel = [];
                                            foreach ($rows as $r) {
                                                if ($r['debit'] > 0) {
                                                    $debitByLabel[$r['label']] = ($debitByLabel[$r['label']] ?? 0) + $r['debit'];
                                                }
                                                if ($r['credit'] > 0) {
                                                    $creditByLabel[$r['label']] = ($creditByLabel[$r['label']] ?? 0) + $r['credit'];
                                                }
                                            }

                                            // Display combined debits
                                            foreach ($debitByLabel as $label => $amt) {
                                                echo '<tr>';
                                                echo '  <td>' . htmlspecialchars($label) . '</td>';
                                                echo '  <td></td>';
                                                echo '  <td class="text-right">USD ' . number_format($amt, 2) . '</td>';
                                                echo '</tr>';
                                            }

                                            // Display combined credits
                                            foreach ($creditByLabel as $label => $amt) {
                                                echo '<tr>';
                                                echo '  <td>&nbsp;&nbsp;' . htmlspecialchars($label) . '</td>';
                                                echo '  <td></td>';
                                                echo '  <td class="text-right">(USD ' . number_format($amt, 2) . ')</td>';
                                                echo '</tr>';
                                            }

                                            // Net Book Value for this code
                                            $sumDebit  = array_sum($debitByLabel);
                                            $sumCredit = array_sum($creditByLabel);
                                            $net       = $sumDebit - $sumCredit;
                                            $netBookValues[] = $net;
                                            $netFmt    = $net < 0
                                                ? '(USD ' . number_format(abs($net), 2) . ')'
                                                : 'USD ' . number_format($net, 2);

                                            echo '<tr>';
                                            echo '  <td><strong>&nbsp;&nbsp;Net Book Value</strong></td>';
                                            echo '  <td></td>';
                                            echo '  <td class="text-right"><strong>' . $netFmt . '</strong></td>';
                                            echo '</tr>';
                                        }
                                    }

                                    // Total Fixed Assets = sum of all group net book values
                                    $total_fixed_assets = array_sum($netBookValues);

                                    if ($total_fixed_assets != 0) {
                                        $totalFmt = $total_fixed_assets < 0
                                            ? '(USD ' . number_format(abs($total_fixed_assets), 2) . ')'
                                            : 'USD ' . number_format($total_fixed_assets, 2);

                                        echo '<tr class="font-weight-bold">';
                                        echo '  <td><strong>Total Fixed Assets</strong></td>';
                                        echo '  <td></td>';
                                        echo '  <td class="text-right"><strong>' . $totalFmt . '</strong></td>';
                                        echo '</tr>';
                                    }
                                    ?>


                    
                                                <!-- Other Assets Header -->
                            <tr style="background-color:#f0f8ff; font-weight:bold;">
                                <td colspan="3">Other Assets</td>
                            </tr>

                            <?php if (!empty($otherasset)): ?>
                                <?php foreach ($otherasset as $asset): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($asset['description']) ?></td>
                                        <td class="text-right"></td>
                                        <td class="text-right"><?= number_format($asset['purchase_price'], 2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="3" class="text-center"></td>
                                </tr>
                            <?php endif; ?>

                            <!-- Total Other Assets -->
                             <?php if ($total_other_assets > 0): ?>
                            <tr style="font-weight:bold;">
                                <td>Total Other Assets</td>
                                <td class="text-right"></td>
                                <td class="text-right"><?= number_format($total_other_assets, 2) ?></td>
                            </tr>
                            <?php endif; ?>

                            <?php
                            // Calculate Total Assets as sum of current, fixed & other assets
                            $total_assets = floatval($total_current_assets  ?? 0)
                                        + floatval($total_fixed_assets    ?? 0)
                                        + floatval($total_other_assets    ?? 0);
                            ?>
                            <tr style="background-color:#d9e1f2; color:black; font-weight:bold;">
                                <td>Total Assets</td>
                                <td class="text-right"></td>
                                <td class="text-right">USD <?= number_format($total_assets, 2) ?></td>
                            </tr>


                <!-- LIABILITIES & OWNER’S EQUITY -->
                <thead style="background-color:#f0f8ff; color:#fff;">
                    <tr><th colspan="3">Liabilities and Owner’s Equity</th></tr>
                </thead>
                <tbody>
                    <!-- Current Liabilities -->
                    <tr style="background-color:#f0f8ff; font-weight:bold;">
                        <td colspan="3">Current Liabilities</td>
                    </tr>
                    <?php
                    // Compute COGS → Accounts Payable
                    $accounts_payable = 0;
                    if (!empty($supplierList) && is_array($supplierList)) {
                        foreach ($supplierList as $supplier) {
                            $price    = isset($supplier['price'])    ? (float)$supplier['price']    : 0;
                            $quantity = isset($supplier['quantity']) ? (float)$supplier['quantity'] : 0;
                            $accounts_payable += $price * $quantity;
                        }
                    }
                    ?>

                    <?php if ($accounts_payable > 0): ?>
                        <tr>
                            <td>Accounts payable</td>
                            <td class="text-right"></td>
                            <td class="text-right">USD <?= number_format($accounts_payable, 2) ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php if ($short_term_loans > 0): ?>
                    <tr>
                        <td>Short‑term loans</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($short_term_loans,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($income_taxes_payable > 0): ?>
                    <tr>
                        <td>Income taxes payable</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($income_taxes_payable,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($accrued_salaries > 0): ?>
                    <tr>
                        <td>Accrued salaries and wages</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($accrued_salaries,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($unearned_revenue > 0): ?>
                    <tr>
                        <td>Unearned revenue</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($unearned_revenue,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($current_portion_debt > 0): ?>
                    <tr>
                        <td>Current portion of long‑term debt</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($current_portion_debt,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php
                    // Sum up all current‐liability balances
                    $total_current_liabilities =
                        $accounts_payable
                        + (float)($short_term_loans       ?? 0)
                        + (float)($income_taxes_payable   ?? 0)
                        + (float)($accrued_salaries       ?? 0)
                        + (float)($unearned_revenue       ?? 0)
                        + (float)($current_portion_debt   ?? 0);
                    ?>

                    <?php if ($total_current_liabilities > 0): ?>
                    <tr style="font-weight:bold;">
                        <td>Total current liabilities</td>
                        <td class="text-right"></td>
                        <td class="text-right">USD <?= number_format($total_current_liabilities, 2) ?></td>
                    </tr>
                    <?php endif; ?>


                    <!-- Long‑Term Liabilities -->
                    <tr style="background-color:#f0f8ff; font-weight:bold;">
                        <td colspan="3">Long‑Term Liabilities</td>
                    </tr>
                    <?php if ($long_term_debt > 0): ?>
                    <tr>
                        <td>Long‑term debt</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($long_term_debt,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($deferred_liabilities > 0): ?>
                    <tr>
                        <td>Deferred income tax</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($deferred_liabilities,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($total_long_term_liabilities > 0): ?>
                    <tr style="font-weight:bold;">
                        <td>Total long-term liabilities</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($total_long_term_liabilities,2) ?></td>
                    </tr>
                    <?php endif; ?>

                    <!-- Owner’s Equity -->
                    <tr style="background-color:#f0f8ff; font-weight:bold;">
                        <td colspan="3">Owner’s Equity</td>
                    </tr>

                    <?php if (!empty($owners_investment) && $owners_investment > 0): ?>
                    <tr>
                        <td>Owner’s investment</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($owners_investment,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    






<!--------------------------------Retained Earnings------------------------------------------>

                     
                   <?php if (isset($net_profit) && $net_profit != 0): ?>
                    <tr>
                        <td>Net Profit</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($net_profit, 2) ?></td>
                    </tr>
                    <?php endif; ?>

                    <?php if (isset($retained_earnings) && $retained_earnings != 0): ?>
                    <tr>
                        <td>Retained Earnings</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($retained_earnings, 2) ?></td>
                    </tr>
                    <?php endif; ?>

                    <?php if (!empty($other_equity) && $other_equity > 0): ?>
                    <tr>
                        <td>Other</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($other_equity,2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php
                        // Calculate Total Owner’s Equity
                        $total_equity = 
                            (float)($other_equity   ?? 0)
                            + (float)($net_profit               ?? 0)
                             + (float)($retained_earnings               ?? 0);
                        ?>

                    <?php if ($total_equity > 0): ?>
                        <tr style="font-weight:bold;">
                            <td>Total Owner’s Equity</td>
                            <td class="text-right"></td>
                            <td class="text-right"><?= number_format($total_equity, 2) ?></td>
                        </tr>
                        <?php endif; ?>

                        <?php
                        // Calculate Total Liabilities & Owner’s Equity
                        $total_liabilities_and_equity = 
                            (float)($total_current_liabilities   ?? 0)
                            + (float)($total_long_term_liabilities ?? 0)
                            + (float)($total_equity               ?? 0);
                        ?>

                    <?php if ($total_liabilities_and_equity > 0): ?>
                    <tr style="background-color:#d9e1f2; color:black; font-weight:bold;">
                        <td>Total Liabilities and Owner’s Equity</td>
                        <td class="text-right"></td>
                        <td class="text-right"><?= number_format($total_liabilities_and_equity, 2) ?></td>
                    </tr>
                    <?php endif; ?>


                </tbody>
            </table>

            <!-- Print Button -->
            <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 ?>"
                        title="Print Balance Sheet">
                    <i class="fa fa-print"></i> Print Balance Sheet
                </button>
                </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php } ?>



<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/balancesheet/printbalancesheet") ?>',
                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>