<?php $currency_symbol = $this->customlib->getSchoolCurrencyFormat(); ?>
<style type="text/css">
    @media print {
        .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
            float: left;
        }
        .col-sm-12 {
            width: 100%;
        }
        .col-sm-11 {
            width: 91.66666667%;
        }
        .col-sm-10 {
            width: 83.33333333%;
        }
        .col-sm-9 {
            width: 75%;
        }
        .col-sm-8 {
            width: 66.66666667%;
        }
        .col-sm-7 {
            width: 58.33333333%;
        }
        .col-sm-6 {
            width: 50%;
        }
        .col-sm-5 {
            width: 41.66666667%;
        }
        .col-sm-4 {
            width: 33.33333333%;
        }
        .col-sm-3 {
            width: 25%;
        }
        .col-sm-2 {
            width: 16.66666667%;
        }
        .col-sm-1 {
            width: 8.33333333%;
        }
        .col-sm-pull-12 {
            right: 100%;
        }
        .col-sm-pull-11 {
            right: 91.66666667%;
        }
        .col-sm-pull-10 {
            right: 83.33333333%;
        }
        .col-sm-pull-9 {
            right: 75%;
        }
        .col-sm-pull-8 {
            right: 66.66666667%;
        }
        .col-sm-pull-7 {
            right: 58.33333333%;
        }
        .col-sm-pull-6 {
            right: 50%;
        }
        .col-sm-pull-5 {
            right: 41.66666667%;
        }
        .col-sm-pull-4 {
            right: 33.33333333%;
        }
        .col-sm-pull-3 {
            right: 25%;
        }
        .col-sm-pull-2 {
            right: 16.66666667%;
        }
        .col-sm-pull-1 {
            right: 8.33333333%;
        }
        .col-sm-pull-0 {
            right: auto;
        }
        .col-sm-push-12 {
            left: 100%;
        }
        .col-sm-push-11 {
            left: 91.66666667%;
        }
        .col-sm-push-10 {
            left: 83.33333333%;
        }
        .col-sm-push-9 {
            left: 75%;
        }
        .col-sm-push-8 {
            left: 66.66666667%;
        }
        .col-sm-push-7 {
            left: 58.33333333%;
        }
        .col-sm-push-6 {
            left: 50%;
        }
        .col-sm-push-5 {
            left: 41.66666667%;
        }
        .col-sm-push-4 {
            left: 33.33333333%;
        }
        .col-sm-push-3 {
            left: 25%;
        }
        .col-sm-push-2 {
            left: 16.66666667%;
        }
        .col-sm-push-1 {
            left: 8.33333333%;
        }
        .col-sm-push-0 {
            left: auto;
        }
        .col-sm-offset-12 {
            margin-left: 100%;
        }
        .col-sm-offset-11 {
            margin-left: 91.66666667%;
        }
        .col-sm-offset-10 {
            margin-left: 83.33333333%;
        }
        .col-sm-offset-9 {
            margin-left: 75%;
        }
        .col-sm-offset-8 {
            margin-left: 66.66666667%;
        }
        .col-sm-offset-7 {
            margin-left: 58.33333333%;
        }
        .col-sm-offset-6 {
            margin-left: 50%;
        }
        .col-sm-offset-5 {
            margin-left: 41.66666667%;
        }
        .col-sm-offset-4 {
            margin-left: 33.33333333%;
        }
        .col-sm-offset-3 {
            margin-left: 25%;
        }
        .col-sm-offset-2 {
            margin-left: 16.66666667%;
        }
        .col-sm-offset-1 {
            margin-left: 8.33333333%;
        }
        .col-sm-offset-0 {
            margin-left: 0%;
        }
        .visible-xs {
            display: none !important;
        }
        .hidden-xs {
            display: block !important;
        }
        table.hidden-xs {
            display: table;
        }
        tr.hidden-xs {
            display: table-row !important;
        }
        th.hidden-xs,
        td.hidden-xs {
            display: table-cell !important;
        }
        .hidden-xs.hidden-print {
            display: none !important;
        }
        .hidden-sm {
            display: none !important;
        }
        .visible-sm {
            display: block !important;
        }
        table.visible-sm {
            display: table;
        }
        tr.visible-sm {
            display: table-row !important;
        }
        th.visible-sm,
        td.visible-sm {
            display: table-cell !important;
        }
    }
</style>

<html lang="en">
    <head>
        <title><?php echo $this->lang->line('fees_receipt'); ?></title>
        <link rel="stylesheet" href="<?php echo base_url(); ?>backend/bootstrap/css/bootstrap.min.css"> 
        <link rel="stylesheet" href="<?php echo base_url(); ?>backend/dist/css/AdminLTE.min.css">
    </head>
    <body> 
        <div class="container">

            <div class="row">

                <div id="content" class="col-lg-12 col-sm-12 ">
                    <div class="invoice">
                        <div class="row header text-center">
                            <div class="col-sm-12">
                                <?php
                                if ($settinglist[0]['image'] != "") {
                                    ?>

                                    <img style="height:70px; " src="<?php echo base_url(); ?>/uploads/school_content/logo/<?php echo $settinglist[0]['image']; ?>"> <br/>
                                    <?php
                                }
                                ?>

                                <strong style="font-size: 20px;"><?php echo $settinglist[0]['name']; ?></strong><br>
                                <?php echo $settinglist[0]['address']; ?><br>

                                <?php echo $this->lang->line('phone'); ?>: <?php echo $settinglist[0]['phone']; ?><br>

                            </div><!--/col-->
                        </div>
                        <div class="row" style="text-align:center;">
                            <div class="col-xs-12">
                                <br/>
                                <address>
                                    <strong><?php echo $exp_title; ?></strong><br/>                                    
                                    <h4 style="color:blue; font-weight:bold;">INCOME STATEMENT REPORT</h4><br/>
                                </address> 
                            </div>
                        </div>

                        <hr style="margin-top: 0px;margin-bottom: 0px;" />
                        <div class="row">
                            
                     <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', '144');
                                    $queryFees = $this->db->get();
                                    $feesRow = $queryFees->row();
                                    $gl_code = $feesRow ? $feesRow->gl_code : 'N/A';
                                    $fees_name = $feesRow ? $feesRow->name : 'Fees Income';
                                    $gl_description = $feesRow ? $feesRow->description : '';

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

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

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

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

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

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

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

                                <!-- 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', '152')
                                        ->get()
                                        ->row();

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

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

                                <!-- 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', '148');
                                $queryUniform = $this->db->get();
                                $uniformRow   = $queryUniform->row();

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

                                <?php 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>
                                            
                                <?php
                            
                            ?>

                        </div>
                    </div>
                </div>  
            </div>
        </div>
        <div class="clearfix"></div>
        <footer>           
        </footer>
    </body>
</html>