<?php
/**
 * CompanyBankAccounts — Slice 8Z-m
 *
 * The OUR-side accounts: where money leaves from when we disburse. Populated by FM + Admin.
 * FM picks one at the Payment Schedule approval step; currency of source must match schedule.
 */
class CompanyBankAccounts extends Model
{
    /** All accounts, optionally filtered by active + currency. */
    public function all(bool $activeOnly = true, string $currency = ''): array
    {
        $db = new DB();
        $where = "WHERE 1=1";
        $p = [];
        if ($activeOnly)      $where .= " AND is_active = 1";
        if ($currency !== '') { $where .= " AND currency = :c"; $p[':c'] = $currency; }
        return $db->mySelect(
            "SELECT * FROM company_bank_accounts $where ORDER BY currency, account_name",
            $p
        ) ?: [];
    }

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

    /** Insert-or-update by id (if id > 0). */
    public function upsert(array $d, int $userId): array
    {
        $name = trim((string)($d['account_name'] ?? ''));
        $acct = trim((string)($d['account_number'] ?? ''));
        $cur  = trim((string)($d['currency'] ?? 'TZS'));
        if ($name === '')                                                     return ['ok' => false, 'msg' => 'Account name required.'];
        if ($acct === '')                                                     return ['ok' => false, 'msg' => 'Account number required.'];
        if (!in_array($cur, ['TZS','USD','EUR','GBP','KES'], true))           return ['ok' => false, 'msg' => 'Invalid currency.'];

        $id  = (int)($d['id'] ?? 0);
        $pid = (int)($d['provider_id'] ?? 0);
        $db  = new DB();
        $providerName = '';
        if ($pid > 0) {
            $pv = $db->mySelect("SELECT provider_name FROM payment_providers WHERE c0d = :id", [':id' => $pid]);
            $providerName = (string)($pv[0]['provider_name'] ?? '');
        }
        $balHint = ($d['balance_hint'] !== '' && $d['balance_hint'] !== null) ? (float)$d['balance_hint'] : null;

        if ($id > 0) {
            $db->insertUpdate(
                "UPDATE company_bank_accounts SET
                    account_name=:n, provider_id=:pid, provider_name=:pnm, account_number=:acc, currency=:cur,
                    branch_name=:br, swift_code=:sw, balance_hint=:bh, notes=:nt,
                    edited_by=:u, edited_on=NOW()
                  WHERE c0d = :id",
                [
                    ':n'=>$name, ':pid'=>$pid ?: null, ':pnm'=>$providerName ?: null,
                    ':acc'=>$acct, ':cur'=>$cur, ':br'=>trim((string)($d['branch_name'] ?? '')) ?: null,
                    ':sw'=>trim((string)($d['swift_code'] ?? '')) ?: null, ':bh'=>$balHint,
                    ':nt'=>trim((string)($d['notes'] ?? '')) ?: null,
                    ':u'=>$userId, ':id'=>$id,
                ]
            );
            return ['ok' => true, 'id' => $id, 'msg' => 'Updated.'];
        }
        $r = $db->insertUpdate(
            "INSERT INTO company_bank_accounts
                (account_name, provider_id, provider_name, account_number, currency, branch_name, swift_code,
                 balance_hint, notes, created_by, edited_by)
             VALUES (:n, :pid, :pnm, :acc, :cur, :br, :sw, :bh, :nt, :u, :u)",
            [
                ':n'=>$name, ':pid'=>$pid ?: null, ':pnm'=>$providerName ?: null,
                ':acc'=>$acct, ':cur'=>$cur, ':br'=>trim((string)($d['branch_name'] ?? '')) ?: null,
                ':sw'=>trim((string)($d['swift_code'] ?? '')) ?: null, ':bh'=>$balHint,
                ':nt'=>trim((string)($d['notes'] ?? '')) ?: null, ':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 company_bank_accounts WHERE c0d = :id", [':id' => $id]);
        if (empty($r)) return ['ok' => false, 'msg' => 'Account not found.'];
        $new = ((int)$r[0]['is_active'] === 1) ? 0 : 1;
        $db->insertUpdate(
            "UPDATE company_bank_accounts 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];
    }
}
