<?php
/**
 * PaymentProviders — Slice 8Z-k
 *
 * Admin-editable lookup for banks / mobile-money operators / cheque. Seeded with the Tanzania
 * default set (M-Pesa, Tigo Pesa, Airtel Money, HaloPesa, T-Pesa, CRDB, NMB, NBC, Stanbic,
 * Exim, DTB, Equity, Absa, KCB, BOA, TIB, Standard Chartered, Azania, Access, I&M, Cheque).
 * New providers can be added without a schema change.
 */
class PaymentProviders extends Model
{
    /** All providers optionally filtered by method + active-only. */
    public function all(string $method = '', bool $activeOnly = true): array
    {
        $db = new DB();
        $where = "WHERE 1=1";
        $p = [];
        if ($activeOnly) $where .= " AND is_active = 1";
        if ($method !== '') { $where .= " AND method = :m"; $p[':m'] = $method; }
        return $db->mySelect(
            "SELECT c0d, provider_code, provider_name, method, is_active, sort_order
               FROM payment_providers $where
              ORDER BY method, sort_order, provider_name",
            $p
        ) ?: [];
    }

    public function byId(int $id): array
    {
        $db = new DB();
        $r = $db->mySelect("SELECT * FROM payment_providers WHERE c0d = :id", [':id' => $id]);
        return $r[0] ?? [];
    }

    /** Upsert by provider_code. Used by both new + edit from the admin surface. */
    public function upsert(array $d, int $userId): array
    {
        $code = strtoupper(trim((string)($d['provider_code'] ?? '')));
        $name = trim((string)($d['provider_name'] ?? ''));
        $method = (string)($d['method'] ?? '');
        if ($code === '')                                           return ['ok' => false, 'msg' => 'Code required.'];
        if ($name === '')                                           return ['ok' => false, 'msg' => 'Name required.'];
        if (!in_array($method, ['MOBILE_MONEY','BANK_TRANSFER','CHEQUE'], true)) return ['ok' => false, 'msg' => 'Invalid method.'];
        $sort = (int)($d['sort_order'] ?? 100);

        $db = new DB();
        $existing = $db->mySelect("SELECT c0d FROM payment_providers WHERE provider_code = :c", [':c' => $code]);
        if (!empty($existing)) {
            $db->insertUpdate(
                "UPDATE payment_providers SET provider_name=:n, method=:m, sort_order=:s, edited_by=:u, edited_on=NOW() WHERE c0d = :id",
                [':n'=>$name, ':m'=>$method, ':s'=>$sort, ':u'=>$userId, ':id'=>(int)$existing[0]['c0d']]
            );
            return ['ok' => true, 'id' => (int)$existing[0]['c0d'], 'msg' => 'Updated.'];
        }
        $r = $db->insertUpdate(
            "INSERT INTO payment_providers (provider_code, provider_name, method, sort_order, created_by, edited_by)
             VALUES (:c, :n, :m, :s, :u, :u)",
            [':c'=>$code, ':n'=>$name, ':m'=>$method, ':s'=>$sort, ':u'=>$userId]
        );
        return ['ok' => true, 'id' => (int)$r['last_id'], 'msg' => 'Created.'];
    }

    public function toggleActive(int $id, int $userId): array
    {
        $db = new DB();
        $r = $db->mySelect("SELECT is_active FROM payment_providers WHERE c0d = :id", [':id' => $id]);
        if (empty($r)) return ['ok' => false, 'msg' => 'Provider not found.'];
        $new = ((int)$r[0]['is_active'] === 1) ? 0 : 1;
        $db->insertUpdate(
            "UPDATE payment_providers SET is_active = :a, edited_by = :u, edited_on = NOW() WHERE c0d = :id",
            [':a'=>$new, ':u'=>$userId, ':id'=>$id]
        );
        return ['ok' => true, 'is_active' => $new];
    }
}
