<?php $this->start('body');
    $groups = $this->data['groups'] ?? [];
    $order  = $this->data['order']  ?? [];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-sitemap me-2 text-muted"></i>Chart of Accounts</h5>
    <a href="<?= PROOT; ?>Journals" class="btn btn-sm btn-outline-secondary"><i class="fas fa-file-alt me-1"></i> All journals</a>
</div>

<?php foreach ($order as $type):
    if (empty($groups[$type])) continue;
    $accent = ['ASSET'=>'#22c55e','LIABILITY'=>'#f59e0b','EQUITY'=>'#8b5cf6','REVENUE'=>'#3b82f6','EXPENSE'=>'#ef4444'][$type] ?? '#64748b';
?>
    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white d-flex align-items-center justify-content-between">
            <strong style="color:<?= $accent; ?>;"><?= ucwords(strtolower($type)); ?></strong>
            <span class="text-muted small"><?= count($groups[$type]); ?> account(s)</span>
        </div>
        <div class="table-responsive">
            <table class="table table-sm mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width:120px;">Code</th><th>Account</th>
                        <th class="text-end">Debits</th><th class="text-end">Credits</th>
                        <th class="text-end">Balance</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($groups[$type] as $r):
                        $bal = (float)$r['presentation_balance'];
                    ?>
                        <tr>
                            <td><code class="text-body"><?= htmlspecialchars($r['account_code']); ?></code>
                                <?php if ((int)$r['is_bank']===1): ?><i class="fas fa-university text-muted ms-1" title="Bank account"></i><?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($r['account_name']); ?></td>
                            <td class="text-end text-muted"><?= (float)$r['total_debit']  > 0 ? number_format((float)$r['total_debit'])  : '—'; ?></td>
                            <td class="text-end text-muted"><?= (float)$r['total_credit'] > 0 ? number_format((float)$r['total_credit']) : '—'; ?></td>
                            <td class="text-end" style="font-weight:600;color:<?= $bal<0?'#ef4444':''; ?>;"><?= number_format($bal); ?></td>
                            <td class="text-end"><a href="<?= PROOT; ?>ChartOfAccounts/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endforeach; ?>

<?php $this->end(); ?>
