<?php $this->start('body');
    $rows = $this->data['rows'] ?? [];
    $methodChip = [
        'MOBILE_MONEY'  => ['#FEF3E7','#8B6914','Mobile money'],
        'BANK_TRANSFER' => ['#EEF2F6','#7A8BA1','Bank transfer'],
        'CHEQUE'        => ['#F1F5F9','#334155','Cheque'],
    ];
?>

<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>Payment providers</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Admin-editable list of banks / mobile-money operators. Drives the destination picker when registering payee accounts.
        </div>
    </div>
    <button type="button" id="btn_add_provider" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
        <i class="fas fa-plus me-1"></i>Add provider
    </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:100px;">Code</th>
                    <th>Name</th>
                    <th style="width:140px;">Method</th>
                    <th class="text-end" style="width:80px;">Sort</th>
                    <th style="width:100px;">Active</th>
                    <th style="width:100px;" class="text-end"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $mc = $methodChip[$r['method']] ?? ['#F1F5F9','#334155',$r['method']];
                ?>
                    <tr data-id="<?= (int)$r['c0d']; ?>" data-code="<?= htmlspecialchars($r['provider_code']); ?>" data-name="<?= htmlspecialchars($r['provider_name']); ?>" data-method="<?= htmlspecialchars($r['method']); ?>" data-sort="<?= (int)$r['sort_order']; ?>">
                        <td class="small"><code><?= htmlspecialchars($r['provider_code']); ?></code></td>
                        <td class="small"><?= htmlspecialchars($r['provider_name']); ?></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="text-end small text-muted"><?= (int)$r['sort_order']; ?></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>
                        <td class="text-end">
                            <button type="button" class="btn btn-sm btn-link p-0 me-2 btn_edit_provider" 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_provider" title="Toggle active"><i class="fas fa-power-off" style="color:<?= (int)$r['is_active'] === 1 ? '#C48579' : '#3F5C43'; ?>;"></i></button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3" style="font-size:.72rem;">No providers yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    function formHtml(cur) {
        cur = cur || {};
        var opt = function (v, c) { return '<option value="' + v + '"' + (c===v?' selected':'') + '>' + v.charAt(0)+v.slice(1).toLowerCase().replace('_',' ') + '</option>'; };
        return '<form id="pv_form">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Code *</label><input name="provider_code" class="form-control form-control-sm" value="' + (cur.code||'') + '" ' + (cur.code ? 'readonly' : '') + ' required></div>' +
              '<div class="col-5"><label class="form-label small">Name *</label><input name="provider_name" class="form-control form-control-sm" value="' + (cur.name||'') + '" required></div>' +
              '<div class="col-3"><label class="form-label small">Sort</label><input type="number" name="sort_order" class="form-control form-control-sm" value="' + (cur.sort||'100') + '"></div>' +
            '</div>' +
            '<label class="form-label small">Method *</label>' +
            '<select name="method" class="form-select form-select-sm">' +
              opt('MOBILE_MONEY', cur.method||'MOBILE_MONEY') +
              opt('BANK_TRANSFER', cur.method||'MOBILE_MONEY') +
              opt('CHEQUE', cur.method||'MOBILE_MONEY') +
            '</select>' +
        '</form>';
    }

    function submitProvider(title, cur) {
        $.confirm({
            title: title, columnClass: 'col-md-6', content: formHtml(cur), type: 'blue',
            buttons: {
                save: { text: 'Save', btnClass: 'btn-primary', action: function () {
                    var f = document.getElementById('pv_form');
                    var payload = {
                        provider_code: f.provider_code.value,
                        provider_name: f.provider_name.value,
                        sort_order:    f.sort_order.value,
                        method:        f.method.value
                    };
                    if (!payload.provider_code.trim() || !payload.provider_name.trim()) { $.alert({title:'Code + Name required', type:'orange'}); return false; }
                    $.post('<?= PROOT; ?>PaymentProviders/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_provider').addEventListener('click', function () {
        submitProvider('Add payment provider', {});
    });

    document.querySelectorAll('.btn_edit_provider').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var tr = this.closest('tr');
            submitProvider('Edit provider · ' + tr.dataset.code, {
                code: tr.dataset.code, name: tr.dataset.name, method: tr.dataset.method, sort: tr.dataset.sort
            });
        });
    });

    document.querySelectorAll('.btn_toggle_provider').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var id = this.closest('tr').dataset.id;
            var name = this.closest('tr').dataset.name;
            $.confirm({
                title: 'Toggle provider?', type: 'orange',
                content: 'Enable / disable <strong>' + name + '</strong>? Disabled providers won\'t appear in destination pickers.',
                buttons: {
                    yes: { text: 'Toggle', btnClass: 'btn-warning', action: function () {
                        $.post('<?= PROOT; ?>PaymentProviders/toggleActiveAj', { id: id }, function (r) {
                            if (r && r.ok) { rsToast('Toggled.', 'success'); setTimeout(function(){location.reload();}, 400); }
                            else $.alert({title:'Could not toggle', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }},
                    cancel: function () {}
                }
            });
        });
    });
})();
</script>

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