<?php

namespace App\Models;

class BankAccount extends BaseModel
{
    protected $fillable = [
        'company_id',
        'account_id',
        'bank_name',
        'account_number',
        'account_name',
        'branch',
        'routing_number',
        'currency_id',
        'opening_balance',
        'is_active',
    ];

    protected $casts = [
        'opening_balance' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    public function account()
    {
        return $this->belongsTo(Account::class);
    }

    public function reconciliations()
    {
        return $this->hasMany(BankReconciliation::class);
    }

    public function label(): string
    {
        $account = $this->relationLoaded('account') ? $this->account : $this->account()->first();

        if ($account) {
            return trim(($account->code ? $account->code . ' — ' : '') . $account->name);
        }

        return $this->bank_name ?: 'Bank account';
    }

    public static function forAccount(int $companyId, Account $account): self
    {
        return static::withoutGlobalScopes()->firstOrCreate(
            [
                'company_id' => $companyId,
                'account_id' => $account->id,
            ],
            [
                'bank_name' => $account->name,
                'account_name' => $account->name,
                'is_active' => true,
            ],
        );
    }
}
