<?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Account extends Model
{
    use HasFactory;

    protected $fillable = ['code', 'name', 'parent_id', 'user_id', 'type', 'is_posting', 'show_in_petty_cash'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
    
    public function parent()
    {
        return $this->belongsTo(Account::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Account::class, 'parent_id');
    }

    public function transactions()
    {
        return $this->hasMany(JournalTransaction::class);
    }

    public function journalTransactions()
    {
        return $this->hasMany(JournalTransaction::class);
    }


    public function getLevelAttribute()
    {
        $level = 0;
        $parent = $this->parent;

        while ($parent) {
            $level++;
            $parent = $parent->parent;
        }

        return $level;
    }



    public function getBalanceAttribute()
    {
        $debit  = $this->journalTransactions()->sum('debit');
        $credit = $this->journalTransactions()->sum('credit');

        return $debit - $credit;
    }



}

