<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

final class BankAccountRepository
{
    public function __construct(private PDO $pdo) {}
    public function search(string $q): array { $where=['1=1']; $params=[]; if($q!==''){ $where[]='(name LIKE ? OR bank_name LIKE ? OR account_no LIKE ? OR iban LIKE ?)'; $like="%{$q}%"; $params=[$like,$like,$like,$like]; } $st=$this->pdo->prepare("SELECT * FROM bank_accounts WHERE ".implode(' AND ',$where)." ORDER BY is_active DESC, id ASC"); $st->execute($params); return $st->fetchAll() ?: []; }
    public function findById(int $id): array|false { $st=$this->pdo->prepare("SELECT * FROM bank_accounts WHERE id=?"); $st->execute([$id]); return $st->fetch(); }
    public function update(int $id, array $d): void { $this->pdo->prepare("UPDATE bank_accounts SET name=?, bank_name=?, account_no=?, iban=?, opening_balance=?, currency_code=?, is_active=?, notes=? WHERE id=?")->execute([$d['name'],$d['bank_name'],$d['account_no'],$d['iban'],$d['opening_balance'],$d['currency_code'],$d['is_active'],$d['notes'],$id]); }
    public function create(array $d): int { $this->pdo->prepare("INSERT INTO bank_accounts (name, bank_name, account_no, iban, opening_balance, currency_code, is_active, notes) VALUES (?,?,?,?,?,?,?,?)")->execute([$d['name'],$d['bank_name'],$d['account_no'],$d['iban'],$d['opening_balance'],$d['currency_code'],$d['is_active'],$d['notes']]); return (int)$this->pdo->lastInsertId(); }
    public function activeAll(): array { return $this->pdo->query("SELECT id,name FROM bank_accounts WHERE is_active=1 ORDER BY name ASC")->fetchAll() ?: []; }
}
