<?php $this->start('body');
    $rows      = $this->data['rows'] ?? [];
    $providers = $this->data['providers'] ?? [];
    $canEdit   = UserGroups::can('CompanyBankAccounts','upsertAj');
?>

<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-vault me-2 text-muted"></i>Company bank accounts</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            OUR-side accounts — where money leaves from when we disburse. FM picks one at each Payment Schedule approval; currency must match the schedule.
        </div>
    </div>
    <?php if ($canEdit): ?>
        <button type="button" id="btn_add_cba" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
            <i class="fas fa-plus me-1"></i>Add account
        </button>
    <?php endif; ?>
</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>Account name</th>
                    <th>Provider</th>
                    <th style="width:80px;">Currency</th>
                    <th>Account number</th>
                    <th>Branch</th>
                    <th class="text-end" style="width:150px;">Balance hint</th>
                    <th style="width:100px;">Active</th>
                    <?php if ($canEdit): ?><th style="width:80px;" class="text-end"></th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $mask = strlen((string)$r['account_number']) > 4
                            ? str_repeat('•', max(3, strlen($r['account_number']) - 4)) . substr($r['account_number'], -4)
                            : $r['account_number'];
                ?>
                    <tr data-id="<?= (int)$r['c0d']; ?>"
                        data-name="<?= htmlspecialchars($r['account_name']); ?>"
                        data-provider-id="<?= (int)($r['provider_id'] ?? 0); ?>"
                        data-account-number="<?= htmlspecialchars($r['account_number']); ?>"
                        data-currency="<?= htmlspecialchars($r['currency']); ?>"
                        data-branch="<?= htmlspecialchars($r['branch_name'] ?? ''); ?>"
                        data-swift="<?= htmlspecialchars($r['swift_code'] ?? ''); ?>"
                        data-balance="<?= htmlspecialchars((string)($r['balance_hint'] ?? '')); ?>"
                        data-notes="<?= htmlspecialchars($r['notes'] ?? ''); ?>">
                        <td class="small"><strong><?= htmlspecialchars($r['account_name']); ?></strong>
                            <?php if (!empty($r['notes'])): ?><div class="text-muted" style="font-size:.62rem;"><?= htmlspecialchars(mb_strimwidth($r['notes'], 0, 80, '…')); ?></div><?php endif; ?>
                        </td>
                        <td class="small text-muted"><?= htmlspecialchars($r['provider_name'] ?: '—'); ?></td>
                        <td><span class="badge" style="background:#EEF2F6;color:#334155;border:1px solid #94A3B8;font-size:.62rem;"><?= htmlspecialchars($r['currency']); ?></span></td>
                        <td class="small"><code><?= htmlspecialchars($mask); ?></code></td>
                        <td class="small text-muted"><?= htmlspecialchars($r['branch_name'] ?: '—'); ?></td>
                        <td class="text-end small text-muted" style="font-size:.62rem;">
                            <?= $r['balance_hint'] !== null ? htmlspecialchars($r['currency']) . ' ' . number_format((float)$r['balance_hint']) : '<em>advisory only</em>'; ?>
                        </td>
                        <td>
                            <?php if ((int)$r['is_active'] === 1): ?>
                                <span class="badge" style="background:#EAF2E8;color:#3F5C43;border:1px solid #3F5C43;font-size:.62rem;">Active</span>
                            <?php else: ?>
                                <span class="badge" style="background:#F5EAE1;color:#C48579;border:1px solid #C48579;font-size:.62rem;">Disabled</span>
                            <?php endif; ?>
                        </td>
                        <?php if ($canEdit): ?>
                            <td class="text-end">
                                <button type="button" class="btn btn-sm btn-link p-0 me-2 btn_edit_cba" title="Edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                                <button type="button" class="btn btn-sm btn-link p-0 btn_toggle_cba" title="Toggle active"><i class="fas fa-power-off" style="color:<?= (int)$r['is_active'] === 1 ? '#C48579' : '#3F5C43'; ?>;"></i></button>
                            </td>
                        <?php endif; ?>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="<?= $canEdit ? 8 : 7; ?>" class="text-center text-muted py-4" style="font-size:.72rem;">No company accounts yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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

    function providerOpts(sel) {
        var o = '<option value="0">— none —</option>';
        PROVIDERS.forEach(function (p) {
            o += '<option value="' + p.c0d + '" data-method="' + p.method + '"' + (parseInt(sel) === parseInt(p.c0d) ? ' selected' : '') + '>' + p.provider_name + ' (' + p.method.toLowerCase().replace('_',' ') + ')</option>';
        });
        return o;
    }

    function formHtml(cur) {
        cur = cur || {};
        var curOpts = ['TZS','USD','EUR','GBP','KES'].map(function (c) {
            return '<option value="' + c + '"' + (cur.currency === c ? ' selected' : '') + '>' + c + '</option>';
        }).join('');
        return '<form id="cba_form">' +
            '<input type="hidden" name="id" value="' + (cur.id || 0) + '">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-8"><label class="form-label small">Account name *</label><input name="account_name" class="form-control form-control-sm" value="' + (cur.name || '') + '" required></div>' +
              '<div class="col-4"><label class="form-label small">Currency *</label><select name="currency" class="form-select form-select-sm">' + curOpts + '</select></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-6"><label class="form-label small">Provider (bank / operator)</label><select name="provider_id" class="form-select form-select-sm">' + providerOpts(cur.provider_id || 0) + '</select></div>' +
              '<div class="col-6"><label class="form-label small">Account / MSISDN *</label><input name="account_number" class="form-control form-control-sm" value="' + (cur.account_number || '') + '" required></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Branch</label><input name="branch_name" class="form-control form-control-sm" value="' + (cur.branch || '') + '"></div>' +
              '<div class="col-4"><label class="form-label small">SWIFT</label><input name="swift_code" class="form-control form-control-sm" value="' + (cur.swift || '') + '"></div>' +
              '<div class="col-4"><label class="form-label small">Balance hint <span class="text-muted" style="font-weight:400;">(advisory)</span></label><input type="number" step="0.01" name="balance_hint" class="form-control form-control-sm" value="' + (cur.balance || '') + '"></div>' +
            '</div>' +
            '<label class="form-label small">Notes</label>' +
            '<textarea name="notes" rows="2" class="form-control form-control-sm">' + (cur.notes || '') + '</textarea>' +
        '</form>';
    }

    function submitCba(title, cur) {
        $.confirm({
            title: title, columnClass: 'col-md-7', type: 'blue',
            content: formHtml(cur),
            buttons: {
                save: { text: 'Save', btnClass: 'btn-primary', action: function () {
                    var f = document.getElementById('cba_form');
                    var payload = {
                        id: f.id.value, account_name: f.account_name.value, currency: f.currency.value,
                        provider_id: f.provider_id.value, account_number: f.account_number.value,
                        branch_name: f.branch_name.value, swift_code: f.swift_code.value,
                        balance_hint: f.balance_hint.value, notes: f.notes.value
                    };
                    if (!payload.account_name.trim() || !payload.account_number.trim()) { $.alert({title:'Name + Account required', type:'orange'}); return false; }
                    $.post('<?= PROOT; ?>CompanyBankAccounts/upsertAj', payload, function (r) {
                        if (r && r.ok) { rsToast(r.msg || 'Saved.', 'success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Could not save', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json').fail(function () { $.alert({title:'Network error', type:'red'}); });
                    return false;
                }},
                cancel: function () {}
            }
        });
    }

    document.getElementById('btn_add_cba').addEventListener('click', function () {
        submitCba('Add company bank account', {});
    });

    document.querySelectorAll('.btn_edit_cba').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var tr = this.closest('tr');
            submitCba('Edit account · ' + tr.dataset.name, {
                id: tr.dataset.id, name: tr.dataset.name, provider_id: tr.dataset.providerId,
                account_number: tr.dataset.accountNumber, currency: tr.dataset.currency,
                branch: tr.dataset.branch, swift: tr.dataset.swift, balance: tr.dataset.balance,
                notes: tr.dataset.notes
            });
        });
    });

    document.querySelectorAll('.btn_toggle_cba').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = this.closest('tr').dataset.id;
            var name = this.closest('tr').dataset.name;
            $.confirm({
                title: 'Toggle account?', type: 'orange',
                content: 'Enable / disable <strong>' + name + '</strong>? Disabled accounts won\'t appear as source at Payment Schedule approval.',
                buttons: {
                    yes: { text: 'Toggle', btnClass: 'btn-warning', action: function () {
                        $.post('<?= PROOT; ?>CompanyBankAccounts/toggleActiveAj', { id: id }, function (r) {
                            if (r && r.ok) { rsToast('Toggled.', 'success'); setTimeout(function(){location.reload();}, 400); }
                            else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
        });
    });
})();
</script>
<?php endif; ?>

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