<?php

namespace App\Models;

use CodeIgniter\Model;

class CreditBalanceModel extends Model
{
    protected $table         = 'credit_balances';
    protected $allowedFields = ['agency_id', 'balance', 'last_updated'];

    public function forAgency(int $agencyId): ?array
    {
        return $this->where('agency_id', $agencyId)->first();
    }

    public function ensureExists(int $agencyId): array
    {
        $existing = $this->forAgency($agencyId);
        if ($existing) {
            return $existing;
        }
        $id = $this->insert(['agency_id' => $agencyId, 'balance' => 0, 'last_updated' => date('Y-m-d H:i:s')], true);
        return $this->find($id);
    }
}
