<?php

namespace App\Models;

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

class ChartOfAccount extends Model
{
    use HasFactory;

    protected $table = 'chart_of_accounts';

    protected $fillable = [
        'company_id',
        'account_category_id',
        'parent_id',
        'name',
        'code',
        'account_type',
        'balance_type',
        'is_parent',
        'description',
        'is_active',
    ];

    protected $casts = [
        'is_parent' => 'boolean',
        'is_active' => 'boolean',
    ];

    // ============ Relationships ============

    /**
     * العلاقة مع شركة الحساب
     */
    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * العلاقة مع فئة الحساب
     */
    public function category()
    {
        return $this->belongsTo(AccountCategory::class, 'account_category_id');
    }

    /**
     * الحساب الأب
     */
    public function parent()
    {
        return $this->belongsTo(ChartOfAccount::class, 'parent_id');
    }

    /**
     * الحسابات الفرعية
     */
    public function children()
    {
        return $this->hasMany(ChartOfAccount::class, 'parent_id', 'id');
    }

    /**
     * أرصدة الحسابات
     */
    public function balances()
    {
        return $this->hasMany(AccountBalance::class, 'chart_of_account_id');
    }

    // ============ Scopes ============

    /**
     * تصفية الحسابات النشطة
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * تصفية حسابات الشركة
     */
    public function scopeForCompany($query, $companyId)
    {
        return $query->where('company_id', $companyId);
    }

    /**
     * تصفية الحسابات الرئيسية فقط
     */
    public function scopeParentOnly($query)
    {
        return $query->where('is_parent', true);
    }

    /**
     * تصفية الحسابات بحسب النوع
     */
    public function scopeByType($query, $type)
    {
        return $query->where('account_type', $type);
    }
}
