<?php
/**
 * PaymentProvidersController — Slice 8Z-k · admin CRUD for the provider lookup.
 *
 * The provider list drives the destination dropdown when a Requester or Accountant registers
 * a payee account. Admin-editable so new banks / mobile-money operators can be added without
 * a schema change.
 */
class PaymentProvidersController extends Controller
{
    public function indexAction()
    {
        $rows = (new PaymentProviders())->all('', false);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('PaymentProviders/index', [
            'page_title' => 'Payment providers',
            'rows'       => $rows,
        ]);
    }

    public function upsertAjAction()
    {
        header('Content-Type: application/json');
        try {
            $r = (new PaymentProviders())->upsert([
                'provider_code' => (string)($_POST['provider_code'] ?? ''),
                'provider_name' => (string)($_POST['provider_name'] ?? ''),
                'method'        => (string)($_POST['method'] ?? ''),
                'sort_order'    => (int)   ($_POST['sort_order'] ?? 100),
            ], $this->currentUserId());
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function toggleActiveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            $r = (new PaymentProviders())->toggleActive($id, $this->currentUserId());
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
