<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'code', 'type', 'bank_name', 'account_number',
        'branch', 'opening_balance', 'current_balance', 'notes', 'is_active',
    ];

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

    public function vouchers()
    {
        return $this->hasMany(Voucher::class);
    }

    public function getBalanceAttribute(): float
    {
        $receipts = (float) $this->vouchers()->where('type', 'receipt')->sum('amount');
        $payments = (float) $this->vouchers()->where('type', 'payment')->sum('amount');
        return (float) $this->opening_balance + $receipts - $payments;
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
