<?php $this->start('body');
    $rows         = $this->data['rows'] ?? [];
    $filterStatus = (string)($this->data['filter_status'] ?? '');
    $filterMethod = (string)($this->data['filter_method'] ?? '');
    $statusChip = [
        'PENDING'  => ['#FEF3E7','#8B6914','Pending'],
        'APPROVED' => ['#EAF2E8','#3F5C43','Approved'],
        'DISABLED' => ['#F5EAE1','#C48579','Disabled'],
    ];
    $methodChip = [
        'MOBILE_MONEY'  => ['#FEF3E7','#8B6914','Mobile money'],
        'BANK_TRANSFER' => ['#EEF2F6','#7A8BA1','Bank transfer'],
        'CHEQUE'        => ['#F1F5F9','#334155','Cheque'],
    ];
    $statusFilters = ['' => 'All', 'PENDING' => 'Pending', 'APPROVED' => 'Approved', 'DISABLED' => 'Disabled'];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-university me-2 text-muted"></i>Payee accounts</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Approve / disable disbursement destinations. Approval is chain-driven — pending accounts route to your FinChains queue.
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-2" style="background:#F8FAFC;">
        <?php foreach ($statusFilters as $k => $lbl):
            $active = ($k === $filterStatus);
        ?>
            <a href="<?= PROOT; ?>PayeeAccounts<?= $k ? '?status=' . $k : ''; ?>" class="btn btn-sm me-1 mb-1"
               style="background:<?= $active ? '#334155' : '#fff'; ?>;color:<?= $active ? '#fff' : '#334155'; ?>;border:1px solid #E2E8F0;font-weight:<?= $active ? 600 : 400; ?>;font-size:.68rem;">
                <?= htmlspecialchars($lbl); ?>
            </a>
        <?php endforeach; ?>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Payee</th>
                    <th style="width:130px;">Method</th>
                    <th>Provider</th>
                    <th>Account / MSISDN</th>
                    <th>Holder</th>
                    <th style="width:130px;">Status</th>
                    <th>Created by</th>
                    <th style="width:140px;" class="text-end">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $mc = $methodChip[$r['method']] ?? ['#F1F5F9','#334155',$r['method']];
                    $sc = $statusChip[$r['status']] ?? ['#F1F5F9','#334155',$r['status']];
                    $acctMasked = strlen((string)$r['account_number']) <= 4
                                  ? $r['account_number']
                                  : str_repeat('•', max(3, strlen($r['account_number']) - 4)) . substr($r['account_number'], -4);
                ?>
                    <tr data-id="<?= (int)$r['c0d']; ?>" data-payee="<?= htmlspecialchars($r['payee_name']); ?>">
                        <td class="small">
                            <strong><?= htmlspecialchars($r['payee_name']); ?></strong>
                            <div class="text-muted" style="font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars(strtolower($r['payee_type'])); ?> #<?= (int)$r['payee_id']; ?></div>
                        </td>
                        <td><span class="badge" style="background:<?= $mc[0]; ?>;color:<?= $mc[1]; ?>;border:1px solid <?= $mc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($mc[2]); ?></span></td>
                        <td class="small"><?= htmlspecialchars($r['provider_name'] ?: '—'); ?></td>
                        <td class="small"><code><?= htmlspecialchars($acctMasked); ?></code>
                            <?php if (!empty($r['branch_name'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars($r['branch_name']); ?></div><?php endif; ?>
                        </td>
                        <td class="small"><?= htmlspecialchars($r['account_holder_name']); ?></td>
                        <td><span class="badge" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($sc[2]); ?></span></td>
                        <td class="text-muted small" style="font-size:.62rem;"><?= htmlspecialchars($r['created_by_name']); ?><div><?= htmlspecialchars(date('d M · H:i', strtotime((string)$r['created_on']))); ?></div></td>
                        <td class="text-end">
                            <?php if ($r['status'] === 'PENDING' && !empty($r['approval_id'])): ?>
                                <a href="<?= PROOT; ?>FinChains/view/<?= (int)$r['approval_id']; ?>" class="btn btn-sm btn-outline-secondary" title="Open approval"><i class="fas fa-check me-1"></i>Approve via chain</a>
                            <?php elseif ($r['status'] === 'APPROVED'): ?>
                                <button type="button" class="btn btn-sm btn-link p-0 btn_disable" title="Disable"><i class="fas fa-power-off" style="color:#C48579;"></i></button>
                            <?php elseif ($r['status'] === 'DISABLED'): ?>
                                <button type="button" class="btn btn-sm btn-link p-0 btn_reactivate" title="Reactivate"><i class="fas fa-undo" style="color:#3F5C43;"></i></button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4" style="font-size:.72rem;">Nothing matches this filter.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    document.querySelectorAll('.btn_disable').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var tr = this.closest('tr'); var id = tr.dataset.id; var name = tr.dataset.payee;
            $.confirm({
                title: 'Disable account?', type: 'red',
                content: '<div class="small mb-2">This will stop <strong>' + name + '</strong>\'s account from being used for any future disbursement.</div>' +
                         '<label class="form-label small">Reason (audit trail) *</label>' +
                         '<textarea id="dis_reason" class="form-control form-control-sm" rows="2" placeholder="e.g. staff resigned, account closed, changed bank"></textarea>',
                buttons: {
                    yes: { text: 'Disable', btnClass: 'btn-danger', action: function () {
                        var reason = (document.getElementById('dis_reason').value || '').trim();
                        if (!reason) { $.alert({title:'Reason required', type:'orange'}); return false; }
                        $.post('<?= PROOT; ?>PayeeAccounts/disableAj', { id: id, reason: reason }, function (r) {
                            if (r && r.ok) { rsToast('Disabled.', 'success'); setTimeout(function(){location.reload();}, 400); }
                            else $.alert({title:'Could not disable', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
        });
    });

    document.querySelectorAll('.btn_reactivate').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = this.closest('tr').dataset.id;
            $.confirm({
                title: 'Reactivate account?', type: 'green',
                content: 'Bring this account back into circulation? It will be available for new disbursements immediately.',
                buttons: {
                    yes: { text: 'Reactivate', btnClass: 'btn-success', action: function () {
                        $.post('<?= PROOT; ?>PayeeAccounts/reactivateAj', { id: id }, function (r) {
                            if (r && r.ok) { rsToast('Reactivated.', 'success'); setTimeout(function(){location.reload();}, 400); }
                            else $.alert({title:'Could not reactivate', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
        });
    });
})();
</script>

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