<?php

declare(strict_types=1);

namespace App\Services;

use App\Shared\Finance\AccountBalanceSupport;
use App\Shared\Schema\FinanceSchemaSupport;
use App\Core\SchemaRuntime;
use App\Repositories\BankAccountRepository;
use InvalidArgumentException;
use PDO;

final class BankAccountService
{
    public function __construct(private PDO $pdo, private BankAccountRepository $repo) {}
    public function ensureSchema(): void { SchemaRuntime::ensure($this->pdo, 'bank_accounts_schema', function (): void { FinanceSchemaSupport::ensureBankAccountsSchema($this->pdo); }, 'sql/migrate_v1_21_bank_accounts.sql'); }
    public function balancesFor(array $accounts): array { $balances=[]; $today=date('Y-m-d'); foreach($accounts as $acc) $balances[(int)$acc['id']] = AccountBalanceSupport::bankAccountBalance($this->pdo, (int)$acc['id'], $today); return $balances; }
    public function loadForm(int $id): array { $account=['id'=>0,'name'=>'','bank_name'=>'','account_no'=>'','iban'=>'','opening_balance'=>'0.00','currency_code'=>'EGP','is_active'=>1,'notes'=>'']; if($id>0){ $row=$this->repo->findById($id); if($row) $account=array_merge($account,$row);} return ['account'=>$account,'errors'=>[],'is_edit'=>$id>0]; }
    public function save(int $id, array $input): void { $a=[]; foreach(['name','bank_name','account_no','iban','opening_balance','currency_code','notes'] as $f) $a[$f]=trim((string)($input[$f] ?? '')); $a['is_active']=(int)($input['is_active'] ?? 1); if($a['name']==='') throw new InvalidArgumentException('اسم الحساب مطلوب.'); if($a['currency_code']==='') $a['currency_code']='EGP'; if(!is_numeric($a['opening_balance'])) throw new InvalidArgumentException('الرصيد الافتتاحي غير صحيح.'); $a['opening_balance']=(float)$a['opening_balance']; $a['currency_code']=strtoupper($a['currency_code']); foreach(['bank_name','account_no','iban','notes'] as $f){ if($a[$f]==='') $a[$f]=null; } if($id>0){ $this->repo->update($id,$a); audit_log('UPDATE_BANK_ACCOUNT', 'bank_accounts', $id, ['name'=>$a['name']]); } else { $newId=$this->repo->create($a); audit_log('CREATE_BANK_ACCOUNT', 'bank_accounts', $newId, ['name'=>$a['name']]); } }
    public function balancesReport(string $q): array { $rows=$this->repo->search($q); $totals=['opening'=>0.0,'current'=>0.0]; foreach($rows as &$r){ $r['current_balance']=AccountBalanceSupport::bankAccountBalance($this->pdo,(int)$r['id']); $totals['opening']+=(float)($r['opening_balance']??0); $totals['current']+=(float)$r['current_balance']; } unset($r); return compact('rows','totals'); }
}
