<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class ChartOfAccount extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'code',
        'name',
        'type',
        'category',
        'description',
        'opening_balance',
        'current_balance',
        'is_active',
        'is_system',
        'parent_id',
        'sort_order',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'opening_balance' => 'decimal:2',
            'current_balance' => 'decimal:2',
            'is_active' => 'boolean',
            'is_system' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    /**
     * Get the parent account
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(ChartOfAccount::class, 'parent_id');
    }

    /**
     * Get child accounts
     */
    public function children(): HasMany
    {
        return $this->hasMany(ChartOfAccount::class, 'parent_id')->orderBy('sort_order');
    }

    /**
     * Get the user who created this account
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get all journal entry lines for this account
     */
    public function journalEntryLines(): HasMany
    {
        return $this->hasMany(JournalEntryLine::class, 'account_id');
    }

    /**
     * Get all expenses for this account
     */
    public function expenses(): HasMany
    {
        return $this->hasMany(Expense::class, 'account_id');
    }

    /**
     * Get all income records for this account
     */
    public function income(): HasMany
    {
        return $this->hasMany(Income::class, 'account_id');
    }

    /**
     * Check if account is a debit account (assets, expenses)
     */
    public function isDebitAccount(): bool
    {
        return in_array($this->type, ['asset', 'expense']);
    }

    /**
     * Check if account is a credit account (liabilities, equity, revenue)
     */
    public function isCreditAccount(): bool
    {
        return in_array($this->type, ['liability', 'equity', 'revenue']);
    }
}
