<?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;">DETAILED OUTSTANDING FEES REPORT</h4><br/>
        </address> 
    </div>
</div>

                        <hr style="margin-top: 0px;margin-bottom: 0px;" />
                        <div class="row">
                        <?php
                                            // Initialize variables
                                            $groupedData = array();
                                            $processedInvoices = array();
                                            $grandTotalSales = 0;
                                            $grandTotalPaid = 0;
                                            $grandTotalBalance = 0;
                                            // First, fetch all exchange rates at once to minimize database queries
                                            $this->db->select('foreign_currency, foreign_rate');
                                            $exchangeRatesQuery = $this->db->get('bank_rates');
                                            $exchangeRates = array();
                                            foreach ($exchangeRatesQuery->result() as $rate) {
                                                $exchangeRates[$rate->foreign_currency] = $rate->foreign_rate;
                                            }
                                            // Group data by student
                                            foreach ($feelist as $rows) {
                                                // Skip the grand total row and duplicates
                                                if (($rows['is_total_row'] ?? false) || isset($processedInvoices[$rows['id']])) {
                                                    continue;
                                                }
                                                $processedInvoices[$rows['id']] = true;
                                                
                                                $studentKey = $rows['student_session_id'] ?? $rows['id'];
                                                if (!isset($groupedData[$studentKey])) {
                                                    $groupedData[$studentKey] = array(
                                                        'name' => ($rows['firstname'] ?? '') . ' ' . ($rows['lastname'] ?? ''),
                                                        'class' => $rows['class_name'] ?? 'N/A',
                                                        'section' => $rows['section_name'] ?? 'N/A',
                                                        'transactions' => array(),
                                                        'total_invoiced' => 0,
                                                        'total_paid' => 0,
                                                        'total_discount' => 0,
                                                        'total_balance' => 0
                                                    );
                                                }
                                                
                                                $amount = $rows['fee_amount'] ?? 0;
                                                $amount_discount = $rows['amount_discount'];
                                                $original_paid = $rows['amount_paid'] ?? 0;
                                                $payment_mode = $rows['payment_mode'] ?? 'USD'; // Default to USD if not specified                                               
                                                // Convert payment to USD if needed
                                                if ($payment_mode !== 'USD' && $original_paid > 0) {
                                                    $foreign_rate = $exchangeRates[$payment_mode] ?? 1;
                                                    $paid = $original_paid / $foreign_rate;
                                                } else {
                                                    $paid = $original_paid;
                                                }
                                                $balance = $amount - ($paid + $amount_discount);
                                                if ($balance == 0 || $balance < 0) continue; 
                                        
                                                $groupedData[$studentKey]['transactions'][] = array(
                                                    'date' => $rows['created_at'],
                                                    'invoice_number' => $rows['invoice_number'],
                                                    'fee_group_name' => $rows['fee_group_name'],
                                                    'discount' => $rows['amount_discount'],
                                                    'amount' => $amount,
                                                    'paid' => $paid,
                                                    'discount' =>$amount_discount,
                                                    'balance' => $balance,
                                                    'payment_mode' => $payment_mode,
                                                    'original_paid' => $original_paid
                                                );                                               
                                                $groupedData[$studentKey]['total_invoiced'] += $amount;
                                                $groupedData[$studentKey]['total_paid'] += $paid;
                                                $groupedData[$studentKey]['total_balance'] += $balance;
                                                $groupedData[$studentKey]['total_discount'] += $amount_discount; 
                                                $grandTotalSales += $amount;
                                                $grandTotalPaid += $paid;
                                                $grandTotalDiscount += $amount_discount;
                                                $grandTotalBalance += $balance;
                                            }
                                            // Remove students with zero or negative balance
                                            foreach ($groupedData as $key => $studentData) {
                                                if ($studentData['total_balance'] <= 0) {
                                                    unset($groupedData[$key]);
                                                }
                                            }
                                           
                                           foreach ($groupedData as $studentId => $studentData): ?>
                                                
                                                <div class="student-section" style="margin-top: 30px; page-break-inside: avoid;">
                                                    <!-- Student Header -->
                                                    <h4 style="margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 8px;">
                                                        <strong>Student:</strong> <?= htmlspecialchars($studentData['name']) ?>
                                                        &nbsp; | &nbsp;
                                                        <strong>Class:</strong> <?= htmlspecialchars($studentData['class']) ?>
                                                        &nbsp; | &nbsp;
                                                        <strong>Section:</strong> <?= htmlspecialchars($studentData['section']) ?>
                                                    </h4>

                                                    <!-- Student's Fees Table -->
                                                    <table class="table table-striped table-bordered" style="width: 100%; margin-bottom: 15px;">
                                                        <thead>
                                                            <tr>
                                                                <th style="width: 15%;">Date</th>
                                                                <th style="width: 20%;">Fee Group</th>
                                                                <th style="width: 10%;">Invoice#</th>
                                                                <th style="width: 13%;" class="text-right">Amount (USD)</th>
                                                                <th style="width: 13%;" class="text-right">Amount Paid (USD)</th>
                                                                <th style="width: 13%;" class="text-right">Discount (USD)</th>
                                                                <th style="width: 18%;" class="text-right">Owing Balance (USD)</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($studentData['transactions'] as $txn): ?>
                                                                <tr>
                                                                    <td><?= date($this->customlib->getSchoolDateFormat(), strtotime($txn['date'])) ?></td>
                                                                    <td><?= htmlspecialchars($txn['fee_group_name']) ?></td>
                                                                    <td><?= htmlspecialchars($txn['invoice_number']) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['amount'], 2) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['paid'], 2) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['discount'], 2) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['balance'], 2) ?></td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight: bold; background-color: #f5f5f5;">
                                                                <td colspan="3" class="text-right">Student Totals:</td>
                                                                <td class="text-right"><?= number_format($studentData['total_invoiced'], 2) ?></td>
                                                                <td class="text-right"><?= number_format($studentData['total_paid'], 2) ?></td>
                                                                 <td class="text-right"><?= number_format($studentData['total_discount'], 2) ?></td>
                                                                <td class="text-right"><?= number_format($studentData['total_balance'], 2) ?></td>
                                                            </tr>
                                                        </tfoot>
                                                    </table>                
                                            <!-- Student Total -->
                                            <div style="text-align: center; margin-top: 8px;">
                                                <p>
                                                    <strong>Closing Balance For <?php echo htmlspecialchars($studentData['name']); ?>:
                                                    USD <?= number_format($studentData['total_balance'], 2) ?></strong>
                                                </p>
                                            </div>
                                                </div>
                                        <?php endforeach; ?>   
                                            <!-- Grand Total Section -->
                                            <div style="margin-top: 30px;">
                                                <table class="table table-bordered" style="width: 100%;">
                                                    <tr style="background-color: #e0e0e0; font-weight: bold;">
                                                    <td style="width: 15%;"></td>
                                                    <td style="width: 15%;"></td>
                                                    <td style="width: 15%;" class="text-right">GRAND TOTAL:</td>
                                                    <td style="width: 13%;" class="text-right"><?= number_format($grandTotalSales, 2) ?></td>
                                                    <td style="width: 13%;" class="text-right"><?= number_format($grandTotalPaid, 2) ?></td>
                                                    <td style="width: 13%;" class="text-right"><?= number_format($grandTotalDiscount, 2) ?></td>
                                                    <td style="width: 18%;" class="text-right"><?= number_format($grandTotalBalance, 2) ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </div>  
                                </div>
                            </div>
                            <div class="clearfix"></div>
                            <footer>           
                            </footer>
                        </body>
</html>