<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 class="content">
    <div class="row">
        <div class="col-md-12">
            <!-- Search Form -->
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">
                        <i class="fa fa-search"></i> <?php echo $this->lang->line('income_statement'); ?>
                    </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/incomestatement/searchstatement'); ?>" 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> Comprehensive Income Statement</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">Comprehensive Income Statement</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;">
                            <tbody>
                                <!-- Revenue Section Header -->
                                <tr style="background-color: #f2f2f2; font-weight: bold;">
                                    <td colspan="2" style="padding: 8px 3px; border-bottom: 2px solid #ddd;">Revenue</td>
                                    <td class="text-right" style="padding: 8px 12px; border-bottom: 2px solid #ddd;"></td>
                                </tr>
                                <?php 
                                    // 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', '100');
                                    $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', '158');
                                    $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', '142');
                                    $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';
                                ?>

                                <!-- Display Sales -->
                                <?php if ($customer_total != 0): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($gl_sales_code) ?></td>
                                        <td><?= htmlspecialchars($sales_description) ?></td>
                                        <td class="text-right">USD <?= number_format($customer_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Display Fees Income -->
                                <?php if ($fees_total != 0): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($gl_code) ?></td>
                                        <td><?= htmlspecialchars($fees_name) ?></td>
                                        <td class="text-right">USD <?= number_format($fees_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Display Uniforms -->
                                <?php if ($uniform_total != 0): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($uniform_gl_code) ?></td>
                                        <td><?= htmlspecialchars($uniform_gl_name) ?></td>
                                        <td class="text-right">USD <?= number_format($uniform_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Display Fine -->
                                <?php if ($fine_total != 0): ?>
                                    <tr>
                                        <td></td>
                                        <td>Add: Fine</td>
                                        <td class="text-right">USD <?= number_format($fine_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Display Less: Sales Returns -->
                                <?php if ($sales_returns_total != 0): ?>
                                    <tr>
                                        <td></td>
                                        <td>Less: Sales Returns</td>
                                        <td class="text-right">USD <?= number_format($sales_returns_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Display Less: Fees Returns -->
                                <?php if ($fees_returns_total != 0): ?>
                                    <tr>
                                        <td></td>
                                        <td>Less: Fees Returns</td>
                                        <td class="text-right">USD <?= number_format($fees_returns_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Display Less: Discounts -->
                                <?php if ($discount_total != 0): ?>
                                    <tr>
                                        <td></td>
                                        <td>Less: Discounts</td>
                                        <td class="text-right">USD <?= number_format($discount_total, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <!-- Total Revenue -->
                                <?php if ($total_revenue != 0): ?>
                                    <tr style="background-color: #f2f2f2; border-bottom: 2px solid #ddd; border-top: 2px solid #ddd; font-weight: bold;">
                                        <td></td>
                                        <td>Total Revenue</td>
                                        <td class="text-right">USD <?= number_format($total_revenue, 2) ?></td>
                                    </tr>
                                <?php endif; ?>
                                 <!-- COS Section -->
                                 <tr style="font-weight: bold;">
                                    <td colspan="3" style="padding: 8px 3px;">Cost of Sales</td>
                                </tr>
                                <?php
                                    // Fetch the GL account for “purchases grocery” (case‐insensitive)
                                    $glAccount = $this->db
                                        ->select('gl_code, name, id')
                                        ->from('glledger_account')
                                        ->where('id', '146')
                                        ->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;
                                    }
                                ?>

                                <!-- COS Section Header -->
                                <?php if ($total_COS != 0): ?>
                                <tr>
                                        <td><?= htmlspecialchars($gl_code) ?></td>
                                        <td><?= htmlspecialchars($gl_name) ?></td>
                                        <td class="text-right">USD <?= number_format($total_COS, 2) ?></td>
                                    </tr>
                                <?php endif; ?>
                                <!-- Single COS total row -->
                                <tr style="background-color: #f2f2f2; border-bottom: 2px solid #ddd; border-top: 2px solid #ddd; font-weight: bold;">
                                    <td></td>
                                    <td>Total Cost of Sales</td>
                                    <td class="text-right" >
                                        USD <?= number_format($total_COS, 2) ?>
                                    </td>
                                </tr>



                                <!-- COGS Section -->
                                <tr style="font-weight: bold;">
                                    <td colspan="3" style="padding: 8px 3px;">Cost of Goods Sold</td>
                                </tr>
                                <?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', '144');
                                $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 if ($total_Labor > 0): ?>
                                    <tr>
                                        <td></td>
                                        <td>Labor</td>
                                        <td class="text-right">USD <?= number_format($total_Labor, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <?php if ($total_Materials > 0): ?>
                                    <!-- Materials row now uses GL details fetched for 'Purchases Uniform' -->
                                    <tr>
                                        <td><?= htmlspecialchars($uniform_gl_code) ?></td>
                                        <td><?= htmlspecialchars($uniform_gl_name) ?></td>
                                        <td class="text-right">USD <?= number_format($total_Materials, 2) ?></td>
                                    </tr>
                                <?php endif; ?>

                                <?php
                                    $total_COGS = $total_Materials + $total_Labor;
                                ?>
                                <tr style="background-color: #f2f2f2; border-bottom: 2px solid #ddd; border-top: 2px solid #ddd; font-weight: bold;">
                                    <td></td>
                                    <td>Total COGS</td>
                                    <td class="text-right" >USD <?= number_format($total_COGS, 2) ?></td>
                                </tr>

                               <!-- Gross Profit -->
                                <?php
                                    // Gross Profit = Total Revenue - Total COS - Total COGS
                                    $gross_profit = $total_revenue - $total_COS - $total_COGS;
                                ?>
                                <tr style="font-weight: bold;">
                                    <td></td>
                                    <td>Gross Profit</td>
                                    <td class="text-right">USD <?= number_format($gross_profit, 2) ?></td>
                                </tr>

                                <!-- Operating Expenses -->
                                <tr style="font-weight: bold;">
                                    <td colspan="3" style="padding: 8px 3px;">Operating Expenses</td>
                                </tr>
                                <?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'];
                                            echo '<tr>';
                                            echo '<td>' . htmlspecialchars($account['code']) . '</td>';
                                            echo '<td>' . htmlspecialchars($account['name']) . '</td>';
                                            echo '<td class="text-right">USD ' . number_format($account['total'], 2) . '</td>';
                                            echo '</tr>';
                                        }
                                    }
                                ?>
                                <tr style="background-color: #f2f2f2; border-bottom: 2px solid #ddd; border-top: 2px solid #ddd; font-weight: bold;">
                                    <td></td>
                                    <td>Total Operating Expenses</td>
                                    <td class="text-right">USD <?= number_format($total_expense, 2) ?></td>
                                </tr>

                                <?php
                                    // Operating Profit = Gross Profit - Total Operating Expenses
                                    $operating_profit = $gross_profit - $total_expense;
                                ?>
                                <!-- Operating Profit Section -->
                                <tr style="font-weight: bold;">
                                    <td></td>
                                    <td>Operating Profit/Loss</td>
                                    <td class="text-right">USD <?= number_format($operating_profit, 2) ?></td>
                                </tr>

                                <?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 if ($other_income_total != 0): ?>
                                    <!-- Other Income Section -->
                                    <tr style="font-weight: bold;">
                                        <td colspan="3" style="padding: 8px 3px;">Add: Other Income</td>
                                    </tr>
                                    <tr>
                                        <td><?= htmlspecialchars($other_gl_code) ?></td>
                                        <td><?= htmlspecialchars($other_gl_name) ?></td>
                                        <td class="text-right">USD <?= number_format($other_income_total, 2) ?></td>
                                    </tr>
                                    <!-- Net Profit/Loss -->
                                    <tr style="background-color: #d9edf7; font-weight: bold;">
                                        <td style="border-top: 2px solid #000;"></td>
                                        <td style="border-top: 2px solid #000;">Net Profit/Loss</td>
                                        <td class="text-right" style="border-top: 2px solid #000;">USD <?= number_format($net_profit, 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 ?>"
                                    data-report_type="<?= $report_type ?>"
                                    title="Print Invoice Summary">
                                <i class="fa fa-print"></i> Print Income Statement
                            </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/incomestatement/printIncomestatement") ?>',
                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>