<?php

namespace App\Models;

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

class ChartOfAccount extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'code',
        'name',
        'type',
        'sub_type',
        'opening_balance',
        'current_balance',
        'description',
        'is_active',
        'is_system_account',
        'parent_id',
        'level'
    ];

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

    // সম্পর্ক
    public function parent()
    {
        return $this->belongsTo(ChartOfAccount::class, 'parent_id');
    }

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

    public function journalEntryItems()
    {
        return $this->hasMany(JournalEntryItem::class);
    }

    // স্কোপস
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeAssets($query)
    {
        return $query->where('type', 'asset');
    }

    public function scopeLiabilities($query)
    {
        return $query->where('type', 'liability');
    }

    public function scopeEquity($query)
    {
        return $query->where('type', 'equity');
    }

    public function scopeIncome($query)
    {
        return $query->where('type', 'income');
    }

    public function scopeExpenses($query)
    {
        return $query->where('type', 'expense');
    }

    // হেল্পার মেথডস
    public function getBalanceAttribute()
    {
        return $this->current_balance;
    }

    public function getTypeNameAttribute()
    {
        $types = [
            'asset' => 'সম্পদ',
            'liability' => 'দায়',
            'equity' => 'মূলধন',
            'income' => 'আয়',
            'expense' => 'ব্যয়'
        ];

        return $types[$this->type] ?? $this->type;
    }

    public function getFullNameAttribute()
    {
        return $this->code . ' - ' . $this->name;
    }
}