<?php $this->start('body');
    $rows      = $this->data['rows'] ?? [];
    $providers = $this->data['providers'] ?? [];
    $statusChip = [
        'PENDING'  => ['#FEF3E7','#8B6914','Pending FM'],
        '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'],
    ];
    // Mask helper (mirror the PHP one — last 4 kept)
?>

<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-piggy-bank me-2 text-muted"></i>My payee accounts</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Register the bank / mobile-money destinations we should pay you into. New accounts need FM approval before they can be used.
        </div>
    </div>
    <button type="button" id="btn_add_account" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
        <i class="fas fa-plus me-1"></i>Register account
    </button>
</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 style="width:130px;">Method</th>
                    <th>Provider</th>
                    <th>Account / MSISDN</th>
                    <th>Holder</th>
                    <th style="width:130px;">Status</th>
                    <th style="width:120px;">Added</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>
                        <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(date('d M · H:i', strtotime((string)$r['created_on']))); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-4" style="font-size:.72rem;">You haven't registered any accounts yet — <a href="#" onclick="document.getElementById('btn_add_account').click();return false;">register one</a> so cash can be paid into it.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    var PROVIDERS = <?= json_encode(array_values($providers)); ?>;

    function optsForMethod(method) {
        var opts = '<option value="">— pick a provider —</option>';
        PROVIDERS.filter(function(p){ return p.method === method; }).forEach(function(p){
            opts += '<option value="' + p.c0d + '">' + p.provider_name + '</option>';
        });
        return opts;
    }

    document.getElementById('btn_add_account').addEventListener('click', function () {
        $.confirm({
            title: 'Register payee account', columnClass: 'col-md-7', type: 'blue',
            content:
                '<form id="ac_form">' +
                  '<div class="row g-2 mb-2">' +
                    '<div class="col-4"><label class="form-label small">Method *</label>' +
                      '<select name="method" id="ac_method" class="form-select form-select-sm">' +
                        '<option value="MOBILE_MONEY">Mobile money</option>' +
                        '<option value="BANK_TRANSFER">Bank transfer</option>' +
                        '<option value="CHEQUE">Cheque</option>' +
                      '</select>' +
                    '</div>' +
                    '<div class="col-8"><label class="form-label small">Provider *</label>' +
                      '<select name="provider_id" id="ac_provider" class="form-select form-select-sm">' + optsForMethod('MOBILE_MONEY') + '</select>' +
                    '</div>' +
                  '</div>' +
                  '<div class="row g-2 mb-2">' +
                    '<div class="col-6"><label class="form-label small">Account number / MSISDN *</label><input name="account_number" class="form-control form-control-sm" required></div>' +
                    '<div class="col-6"><label class="form-label small">Account holder name *</label><input name="account_holder_name" class="form-control form-control-sm" required></div>' +
                  '</div>' +
                  '<div class="row g-2 mb-2">' +
                    '<div class="col-6"><label class="form-label small">Branch (banks)</label><input name="branch_name" class="form-control form-control-sm"></div>' +
                    '<div class="col-6"><label class="form-label small">SWIFT (banks, optional)</label><input name="swift_code" class="form-control form-control-sm"></div>' +
                  '</div>' +
                  '<label class="form-label small">Notes</label>' +
                  '<textarea name="notes" rows="2" class="form-control form-control-sm" placeholder="Anything FM should know before approving?"></textarea>' +
                '</form>' +
                '<div class="alert py-2 mt-2 mb-0 small" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.65rem;">' +
                  '<i class="fas fa-info-circle me-1"></i>' +
                  'New accounts start <strong>PENDING</strong>. Finance Manager approves before it becomes a permanent destination — but Accountant can accept it ad-hoc for a single disbursement with a mandatory reason.' +
                '</div>',
            onOpen: function () {
                document.getElementById('ac_method').addEventListener('change', function () {
                    document.getElementById('ac_provider').innerHTML = optsForMethod(this.value);
                });
            },
            buttons: {
                save: { text: 'Submit for approval', btnClass: 'btn-success', action: function () {
                    var f = document.getElementById('ac_form');
                    if (!f.account_holder_name.value.trim()) { $.alert({title:'Holder name required',type:'orange'}); return false; }
                    if (f.method.value !== 'CHEQUE' && !f.account_number.value.trim()) { $.alert({title:'Account / MSISDN required',type:'orange'}); return false; }
                    var payload = {
                        payee_type: 'STAFF', payee_name: '', // controller defaults to session user
                        method: f.method.value, provider_id: f.provider_id.value,
                        account_number: f.account_number.value, account_holder_name: f.account_holder_name.value,
                        branch_name: f.branch_name.value, swift_code: f.swift_code.value, notes: f.notes.value
                    };
                    $.post('<?= PROOT; ?>PayeeAccounts/newAj', payload, function (r) {
                        if (r && r.ok) { rsToast(r.msg || 'Submitted.', 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Could not submit', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>

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