<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class MemberLedger extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'member_ledgers';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'member_id',
        'transaction_date',
        'transaction_type',
        'transaction_subtype',
        'voucher_no',
        'description',
        'reference_no',
        'reference_type',
        'reference_id',
        'debit_amount',
        'credit_amount',
        'balance',
        'remarks',
        'created_by',
        'updated_by',
        'status',
        'is_reconciled',
        'reconciled_date',
        'reconciled_by',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'transaction_date' => 'date',
        'debit_amount' => 'decimal:2',
        'credit_amount' => 'decimal:2',
        'balance' => 'decimal:2',
        'is_reconciled' => 'boolean',
        'reconciled_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * The attributes that should be appended.
     *
     * @var array
     */
    protected $appends = [
        'formatted_transaction_date',
        'formatted_debit_amount',
        'formatted_credit_amount',
        'formatted_balance',
        'transaction_type_bangla',
        'transaction_nature',
    ];

    /**
     * ট্রানজেকশন টাইপ কনস্ট্যান্ট
     */
    const TYPE_SAVING = 'saving';
    const TYPE_LOAN_DISBURSEMENT = 'loan_disbursement';
    const TYPE_LOAN_INSTALLMENT = 'loan_installment';
    const TYPE_LOAN_INTEREST = 'loan_interest';
    const TYPE_LOAN_PENALTY = 'loan_penalty';
    const TYPE_INCOME = 'income';
    const TYPE_EXPENSE = 'expense';
    const TYPE_ADJUSTMENT = 'adjustment';
    const TYPE_TRANSFER = 'transfer';
    const TYPE_OPENING_BALANCE = 'opening_balance';
    const TYPE_CLOSING_BALANCE = 'closing_balance';
    const TYPE_OTHER = 'other';

    /**
     * ট্রানজেকশন স্ট্যাটাস কনস্ট্যান্ট
     */
    const STATUS_PENDING = 'pending';
    const STATUS_COMPLETED = 'completed';
    const STATUS_CANCELLED = 'cancelled';
    const STATUS_REVERSED = 'reversed';

    /**
     * মডেলের বুট মেথড
     */
    protected static function boot()
    {
        parent::boot();

        // নতুন রেকর্ড তৈরি করার সময় ভাউচার নং জেনারেট করা
        static::creating(function ($model) {
            if (empty($model->voucher_no)) {
                $model->voucher_no = self::generateVoucherNumber();
            }
            
            if (empty($model->status)) {
                $model->status = self::STATUS_COMPLETED;
            }
            
            if (Auth::check() && empty($model->created_by)) {
                $model->created_by = Auth::id();
            }
        });

        // রেকর্ড আপডেট করার সময় আপডেটেড_by সেট করা
        static::updating(function ($model) {
            if (Auth::check() && empty($model->updated_by)) {
                $model->updated_by = Auth::id();
            }
        });

        // ব্যালেন্স ক্যালকুলেশন
        static::saved(function ($model) {
            $model->updateMemberBalance();
        });
    }

    /**
     * মেম্বারের সাথে সম্পর্ক
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function member()
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    /**
     * ক্রিয়েটারের সাথে সম্পর্ক
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * আপডেটারের সাথে সম্পর্ক
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * রিকনসিলড বাইয়ের সাথে সম্পর্ক
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function reconciler()
    {
        return $this->belongsTo(User::class, 'reconciled_by');
    }

    /**
     * মাসিক সঞ্চয়ের সাথে সম্পর্ক (যদি থাকে)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function monthlySaving()
    {
        return $this->belongsTo(MonthlySaving::class, 'reference_id')
            ->where('reference_type', 'monthly_saving');
    }

    /**
     * ঋণের সাথে সম্পর্ক (যদি থাকে)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function loan()
    {
        return $this->belongsTo(Loan::class, 'reference_id')
            ->where('reference_type', 'loan');
    }

    /**
     * ঋণ কিস্তির সাথে সম্পর্ক (যদি থাকে)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function loanInstallment()
    {
        return $this->belongsTo(LoanInstallment::class, 'reference_id')
            ->where('reference_type', 'loan_installment');
    }

    /**
     * আয়ের সাথে সম্পর্ক (যদি থাকে)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function income()
    {
        return $this->belongsTo(Income::class, 'reference_id')
            ->where('reference_type', 'income');
    }

    /**
     * ব্যয়ের সাথে সম্পর্ক (যদি থাকে)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function expense()
    {
        return $this->belongsTo(Expense::class, 'reference_id')
            ->where('reference_type', 'expense');
    }

    /**
     * ফরম্যাটেড ট্রানজেকশন তারিখ
     *
     * @return string
     */
    public function getFormattedTransactionDateAttribute()
    {
        return date('d/m/Y', strtotime($this->transaction_date));
    }

    /**
     * ফরম্যাটেড ডেবিট অ্যামাউন্ট
     *
     * @return string
     */
    public function getFormattedDebitAmountAttribute()
    {
        return number_format($this->debit_amount, 2);
    }

    /**
     * ফরম্যাটেড ক্রেডিট অ্যামাউন্ট
     *
     * @return string
     */
    public function getFormattedCreditAmountAttribute()
    {
        return number_format($this->credit_amount, 2);
    }

    /**
     * ফরম্যাটেড ব্যালেন্স
     *
     * @return string
     */
    public function getFormattedBalanceAttribute()
    {
        return number_format($this->balance, 2);
    }

    /**
     * ট্রানজেকশন টাইপ বাংলা
     *
     * @return string
     */
    public function getTransactionTypeBanglaAttribute()
    {
        $types = [
            self::TYPE_SAVING => 'সঞ্চয়',
            self::TYPE_LOAN_DISBURSEMENT => 'ঋণ গ্রহণ',
            self::TYPE_LOAN_INSTALLMENT => 'ঋণ কিস্তি',
            self::TYPE_LOAN_INTEREST => 'ঋণ সুদ',
            self::TYPE_LOAN_PENALTY => 'ঋণ জরিমানা',
            self::TYPE_INCOME => 'আয়',
            self::TYPE_EXPENSE => 'ব্যয়',
            self::TYPE_ADJUSTMENT => 'সংশোধন',
            self::TYPE_TRANSFER => 'স্থানান্তর',
            self::TYPE_OPENING_BALANCE => 'ওপেনিং ব্যালেন্স',
            self::TYPE_CLOSING_BALANCE => 'ক্লোজিং ব্যালেন্স',
            self::TYPE_OTHER => 'অন্যান্য',
        ];

        return $types[$this->transaction_type] ?? 'অন্যান্য';
    }

    /**
     * ট্রানজেকশন প্রকৃতি (ডেবিট/ক্রেডিট)
     *
     * @return string
     */
    public function getTransactionNatureAttribute()
    {
        if ($this->debit_amount > 0) {
            return 'debit';
        } elseif ($this->credit_amount > 0) {
            return 'credit';
        }
        
        return 'neutral';
    }

    /**
     * নেট অ্যামাউন্ট (ক্রেডিট - ডেবিট)
     *
     * @return float
     */
    public function getNetAmountAttribute()
    {
        return $this->credit_amount - $this->debit_amount;
    }

    /**
     * ফরম্যাটেড নেট অ্যামাউন্ট
     *
     * @return string
     */
    public function getFormattedNetAmountAttribute()
    {
        return number_format($this->net_amount, 2);
    }

    /**
     * ভাউচার নম্বর জেনারেট করুন
     *
     * @return string
     */
    public static function generateVoucherNumber()
    {
        $prefix = 'VL';
        $year = date('Y');
        $month = date('m');
        
        $lastRecord = self::where('voucher_no', 'like', "{$prefix}{$year}{$month}%")
            ->orderBy('voucher_no', 'desc')
            ->first();
        
        if ($lastRecord) {
            $lastNumber = intval(substr($lastRecord->voucher_no, -5));
            $nextNumber = str_pad($lastNumber + 1, 5, '0', STR_PAD_LEFT);
        } else {
            $nextNumber = '00001';
        }
        
        return "{$prefix}{$year}{$month}{$nextNumber}";
    }

    /**
     * মেম্বারের ব্যালেন্স আপডেট করুন
     *
     * @return void
     */
    public function updateMemberBalance()
    {
        try {
            if ($this->member) {
                $transactions = self::where('member_id', $this->member_id)
                    ->orderBy('transaction_date', 'asc')
                    ->orderBy('id', 'asc')
                    ->get();
                
                $runningBalance = 0;
                
                foreach ($transactions as $transaction) {
                    $runningBalance += ($transaction->credit_amount - $transaction->debit_amount);
                    
                    // Avoid infinite loop by checking if balance has changed
                    if ($transaction->balance != $runningBalance) {
                        $transaction->balance = $runningBalance;
                        // Use update instead of save to avoid triggering the saved event again
                        self::where('id', $transaction->id)->update(['balance' => $runningBalance]);
                    }
                }
            }
        } catch (\Exception $e) {
            \Log::error('Error updating member balance: ' . $e->getMessage());
        }
    }

    /**
     * সঞ্চয় ট্রানজেকশন তৈরি করুন
     *
     * @param MonthlySaving $saving
     * @return MemberLedger
     */
    public static function createFromSaving(MonthlySaving $saving)
    {
        // শেষ ব্যালেন্স পাওয়া
        $lastLedger = self::where('member_id', $saving->member_id)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        $balance = $lastLedger ? $lastLedger->balance : 0;
        
        return self::create([
            'member_id' => $saving->member_id,
            'transaction_date' => $saving->payment_date ?? now(),
            'transaction_type' => self::TYPE_SAVING,
            'transaction_subtype' => 'monthly_saving',
            'voucher_no' => $saving->receipt_no ?? self::generateVoucherNumber(),
            'description' => 'মাসিক সঞ্চয় - ' . ($saving->month_year ?? date('F Y')),
            'reference_no' => $saving->receipt_no,
            'reference_type' => 'monthly_saving',
            'reference_id' => $saving->id,
            'debit_amount' => 0,
            'credit_amount' => $saving->amount,
            'balance' => $balance + $saving->amount,
            'remarks' => 'মাসিক সঞ্চয় আদায়',
            'status' => ($saving->status ?? 'paid') == 'paid' ? self::STATUS_COMPLETED : self::STATUS_PENDING,
        ]);
    }

    /**
     * ঋণ বিতরণ ট্রানজেকশন তৈরি করুন
     *
     * @param Loan $loan
     * @return MemberLedger
     */
    public static function createFromLoanDisbursement(Loan $loan)
    {
        $lastLedger = self::where('member_id', $loan->member_id)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        $balance = $lastLedger ? $lastLedger->balance : 0;
        
        return self::create([
            'member_id' => $loan->member_id,
            'transaction_date' => $loan->disbursement_date ?? now(),
            'transaction_type' => self::TYPE_LOAN_DISBURSEMENT,
            'transaction_subtype' => 'loan_disbursement',
            'voucher_no' => $loan->loan_number ?? self::generateVoucherNumber(),
            'description' => 'ঋণ গ্রহণ - ' . ($loan->purpose ?? 'ঋণ'),
            'reference_no' => $loan->loan_number,
            'reference_type' => 'loan',
            'reference_id' => $loan->id,
            'debit_amount' => $loan->amount,
            'credit_amount' => 0,
            'balance' => $balance - $loan->amount,
            'remarks' => 'ঋণ বিতরণ করা হয়েছে',
            'status' => ($loan->status ?? 'disbursed') == 'disbursed' ? self::STATUS_COMPLETED : self::STATUS_PENDING,
        ]);
    }

    /**
     * ঋণ কিস্তি ট্রানজেকশন তৈরি করুন
     *
     * @param LoanInstallment $installment
     * @return MemberLedger
     */
    public static function createFromLoanInstallment(LoanInstallment $installment)
    {
        // Check if loan exists and has member_id
        if (!$installment->loan || !$installment->loan->member_id) {
            return null;
        }
        
        $lastLedger = self::where('member_id', $installment->loan->member_id)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        $balance = $lastLedger ? $lastLedger->balance : 0;
        
        return self::create([
            'member_id' => $installment->loan->member_id,
            'transaction_date' => $installment->payment_date ?? now(),
            'transaction_type' => self::TYPE_LOAN_INSTALLMENT,
            'transaction_subtype' => 'loan_repayment',
            'voucher_no' => $installment->receipt_no ?? self::generateVoucherNumber(),
            'description' => 'ঋণ কিস্তি - ' . ($installment->loan->loan_number ?? 'ঋণ') . ' (কিস্তি: ' . $installment->installment_no . ')',
            'reference_no' => $installment->receipt_no,
            'reference_type' => 'loan_installment',
            'reference_id' => $installment->id,
            'debit_amount' => 0,
            'credit_amount' => $installment->amount,
            'balance' => $balance + $installment->amount,
            'remarks' => 'ঋণ কিস্তি পরিশোধ',
            'status' => ($installment->status ?? 'paid') == 'paid' ? self::STATUS_COMPLETED : self::STATUS_PENDING,
        ]);
    }

    /**
     * আয় ট্রানজেকশন তৈরি করুন
     *
     * @param Income $income
     * @return MemberLedger|null
     */
    public static function createFromIncome(Income $income)
    {
        if (!$income->member_id) {
            return null;
        }
        
        $lastLedger = self::where('member_id', $income->member_id)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        $balance = $lastLedger ? $lastLedger->balance : 0;
        
        return self::create([
            'member_id' => $income->member_id,
            'transaction_date' => $income->income_date ?? now(),
            'transaction_type' => self::TYPE_INCOME,
            'transaction_subtype' => $income->category ?? 'other',
            'voucher_no' => $income->receipt_no ?? self::generateVoucherNumber(),
            'description' => 'আয় - ' . ($income->category ?? 'আয়') . ': ' . ($income->description ?? ''),
            'reference_no' => $income->receipt_no,
            'reference_type' => 'income',
            'reference_id' => $income->id,
            'debit_amount' => 0,
            'credit_amount' => $income->amount,
            'balance' => $balance + $income->amount,
            'remarks' => $income->remarks,
            'status' => self::STATUS_COMPLETED,
        ]);
    }

    /**
     * ব্যয় ট্রানজেকশন তৈরি করুন
     *
     * @param Expense $expense
     * @return MemberLedger|null
     */
    public static function createFromExpense(Expense $expense)
    {
        if (!$expense->member_id) {
            return null;
        }
        
        $lastLedger = self::where('member_id', $expense->member_id)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        $balance = $lastLedger ? $lastLedger->balance : 0;
        
        return self::create([
            'member_id' => $expense->member_id,
            'transaction_date' => $expense->expense_date ?? now(),
            'transaction_type' => self::TYPE_EXPENSE,
            'transaction_subtype' => $expense->category ?? 'other',
            'voucher_no' => $expense->voucher_no ?? self::generateVoucherNumber(),
            'description' => 'ব্যয় - ' . ($expense->category ?? 'ব্যয়') . ': ' . ($expense->description ?? ''),
            'reference_no' => $expense->voucher_no,
            'reference_type' => 'expense',
            'reference_id' => $expense->id,
            'debit_amount' => $expense->amount,
            'credit_amount' => 0,
            'balance' => $balance - $expense->amount,
            'remarks' => $expense->remarks,
            'status' => self::STATUS_COMPLETED,
        ]);
    }

    /**
     * ম্যানুয়াল লেজার এন্ট্রি তৈরি করুন
     *
     * @param array $data
     * @return MemberLedger
     */
    public static function createManualEntry(array $data)
    {
        $lastLedger = self::where('member_id', $data['member_id'])
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        $balance = $lastLedger ? $lastLedger->balance : 0;
        
        if ($data['transaction_nature'] === 'debit') {
            $debitAmount = $data['amount'];
            $creditAmount = 0;
            $newBalance = $balance - $data['amount'];
        } else {
            $debitAmount = 0;
            $creditAmount = $data['amount'];
            $newBalance = $balance + $data['amount'];
        }
        
        return self::create([
            'member_id' => $data['member_id'],
            'transaction_date' => $data['transaction_date'] ?? now(),
            'transaction_type' => $data['transaction_type'] ?? self::TYPE_OTHER,
            'transaction_subtype' => $data['transaction_subtype'] ?? null,
            'voucher_no' => $data['voucher_no'] ?? self::generateVoucherNumber(),
            'description' => $data['description'],
            'reference_no' => $data['reference_no'] ?? null,
            'reference_type' => $data['reference_type'] ?? null,
            'reference_id' => $data['reference_id'] ?? null,
            'debit_amount' => $debitAmount,
            'credit_amount' => $creditAmount,
            'balance' => $newBalance,
            'remarks' => $data['remarks'] ?? null,
            'status' => $data['status'] ?? self::STATUS_COMPLETED,
        ]);
    }

    /**
     * নির্দিষ্ট মেম্বারের জন্য লেজার এন্ট্রি খুঁজুন
     *
     * @param int $memberId
     * @param string $startDate
     * @param string $endDate
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getLedgerForMember($memberId, $startDate = null, $endDate = null)
    {
        $query = self::where('member_id', $memberId)
            ->orderBy('transaction_date', 'asc')
            ->orderBy('id', 'asc');
        
        if ($startDate) {
            $query->where('transaction_date', '>=', $startDate);
        }
        
        if ($endDate) {
            $query->where('transaction_date', '<=', $endDate);
        }
        
        return $query->get();
    }

    /**
     * নির্দিষ্ট তারিখে ওপেনিং ব্যালেন্স পান
     *
     * @param int $memberId
     * @param string $date
     * @return float
     */
    public static function getOpeningBalance($memberId, $date)
    {
        $lastLedger = self::where('member_id', $memberId)
            ->where('transaction_date', '<', $date)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        return $lastLedger ? $lastLedger->balance : 0;
    }

    /**
     * ট্রানজেকশন রিভার্স করুন
     *
     * @return MemberLedger|null
     */
    public function reverseTransaction()
    {
        if ($this->status == self::STATUS_COMPLETED) {
            $reversal = $this->replicate();
            $reversal->transaction_date = now();
            $reversal->debit_amount = $this->credit_amount;
            $reversal->credit_amount = $this->debit_amount;
            $reversal->description = 'বিপরীত - ' . $this->description;
            $reversal->remarks = 'মূল ট্রানজেকশন রিভার্স করা হয়েছে: ' . $this->voucher_no;
            $reversal->reference_no = 'REV-' . $this->voucher_no;
            $reversal->status = self::STATUS_REVERSED;
            $reversal->created_by = Auth::id() ?? $this->created_by;
            $reversal->save();
            
            $this->status = self::STATUS_REVERSED;
            $this->save();
            
            return $reversal;
        }
        
        return null;
    }

    /**
     * স্কোপ: সম্পূর্ণ ট্রানজেকশন
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeCompleted($query)
    {
        return $query->where('status', self::STATUS_COMPLETED);
    }

    /**
     * স্কোপ: নির্দিষ্ট টাইপের ট্রানজেকশন
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $type
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('transaction_type', $type);
    }

    /**
     * স্কোপ: নির্দিষ্ট সময়ের মধ্যে
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param string $startDate
     * @param string $endDate
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeBetweenDates($query, $startDate, $endDate)
    {
        return $query->whereBetween('transaction_date', [$startDate, $endDate]);
    }

    /**
     * স্কোপ: রিকনসাইল করা
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeReconciled($query)
    {
        return $query->where('is_reconciled', true);
    }

    /**
     * স্কোপ: রিকনসাইল করা হয়নি
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeUnreconciled($query)
    {
        return $query->where('is_reconciled', false);
    }

    /**
     * ট্রানজেকশন এক্সপোর্ট ডেটা
     *
     * @return array
     */
    public function exportData()
    {
        return [
            'তারিখ' => $this->formatted_transaction_date,
            'ভাউচার নং' => $this->voucher_no,
            'লেনদেনের ধরণ' => $this->transaction_type_bangla,
            'বিবরণ' => $this->description,
            'ডেবিট (টাকা)' => $this->formatted_debit_amount,
            'ক্রেডিট (টাকা)' => $this->formatted_credit_amount,
            'ব্যালেন্স (টাকা)' => $this->formatted_balance,
            'স্ট্যাটাস' => $this->status == self::STATUS_COMPLETED ? 'সম্পন্ন' : 'বকেয়া',
            'মন্তব্য' => $this->remarks,
        ];
    }

    /**
     * লেজার সারাংশ
     *
     * @param int $memberId
     * @param string $startDate
     * @param string $endDate
     * @return array
     */
    public static function getLedgerSummary($memberId, $startDate, $endDate)
    {
        $transactions = self::getLedgerForMember($memberId, $startDate, $endDate);
        
        $summary = [
            'total_debit' => $transactions->sum('debit_amount'),
            'total_credit' => $transactions->sum('credit_amount'),
            'opening_balance' => self::getOpeningBalance($memberId, $startDate),
            'closing_balance' => $transactions->last()->balance ?? 0,
            'transaction_count' => $transactions->count(),
            'by_type' => $transactions->groupBy('transaction_type')->map(function($group) {
                return [
                    'count' => $group->count(),
                    'total_debit' => $group->sum('debit_amount'),
                    'total_credit' => $group->sum('credit_amount'),
                ];
            }),
        ];
        
        return $summary;
    }

    /**
     * মেম্বারের সর্বশেষ ব্যালেন্স পান
     *
     * @param int $memberId
     * @return float
     */
    public static function getCurrentBalance($memberId)
    {
        $lastLedger = self::where('member_id', $memberId)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('id', 'desc')
            ->first();
        
        return $lastLedger ? $lastLedger->balance : 0;
    }
}