<?php

namespace App\Models;

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

class UserAccount extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id','name','account_number','type','opening_balance','status'
    ];

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

    public function user() { return $this->belongsTo(User::class); }

    public function ledgers() { return $this->hasMany(AccountLedger::class, 'user_account_id'); }

    // Current Balance = opening_balance + sum(debit-credit) from account_ledgers
    public function getCurrentBalanceAttribute()
    {
        $sum = $this->ledgers()->selectRaw('COALESCE(SUM(debit),0) as d, COALESCE(SUM(credit),0) as c')->first();
        return (float)$this->opening_balance + ((float)$sum->d - (float)$sum->c);
    }
}