<?= $this->extend('layouts/owner') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="card shadow-sm">
        <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
            <h4 class="mb-0">Laporan Keuangan</h4>
        </div>
        
        <div class="card-body">
            <!-- Filter Sederhana -->
            <form action="<?= base_url('owner/reportfinance') ?>" method="get" class="row mb-4">
                <div class="col-md-3">
                    <select name="bulan" class="form-control">
                        <option value="">-- Pilih Bulan --</option>
                        <?php for($m=1; $m<=12; $m++): ?>
                            <option value="<?= $m ?>" <?= (request()->getGet('bulan') == $m) ? 'selected' : '' ?>>
                                <?= date('F', mktime(0, 0, 0, $m, 1)) ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>Tanggal</th>
                            <th>No. Order</th>
                            <th>Produk</th>
                            <th>Qty</th>
                            <th>Harga</th>
                            <th>Subtotal</th>
                        </tr>
                    </thead>
                  <tbody>
    <?php 
    // INISIALISASI VARIABEL DI SINI agar tidak undefined
    $grandTotal = 0; 
    
    if(empty($reports)): ?>
        <tr>
            <td colspan="6" class="text-center text-muted">Data tidak ditemukan.</td>
        </tr>
    <?php else: ?>
        <?php foreach($reports as $r): 
            $grandTotal += $r['subtotal'];
        ?>
        <tr>
            <td><?= esc($r['tanggal_order']) ?></td>
            <td><?= esc($r['nomor_order']) ?></td>
            <td><?= esc($r['nama_product']) ?></td>
            <td><?= number_format($r['qty']) ?></td>
            <td>Rp <?= number_format($r['harga']) ?></td>
            <td>Rp <?= number_format($r['subtotal']) ?></td>
        </tr>
        <?php endforeach; ?>
    <?php endif; ?>
</tbody>
<tfoot class="table-dark">
    <tr>
        <td colspan="5" class="text-end fw-bold">Total Pendapatan</td>
        <!-- Variabel $grandTotal sekarang pasti terdefinisi -->
        <td class="fw-bold">Rp <?= number_format($grandTotal) ?></td>
    </tr>
</tfoot>
                </table>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>