<?php

namespace App\Models;

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

class AccountHead extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'parent_id',
        'head_code',
        'head_name',
        'head_type',
        'description',
        'is_active',
    ];

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

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

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

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

    public function ledgerEntries()
    {
        return $this->hasMany(LedgerEntry::class, 'account_head_id');
    }

    public function budgets()
    {
        return $this->hasMany(Budget::class, 'account_head_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

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

    public function scopeRootHeads($query)
    {
        return $query->whereNull('parent_id');
    }

    public function scopeSearch($query, $search)
    {
        return $query->where(function($q) use ($search) {
            $q->where('head_name', 'like', "%{$search}%")
              ->orWhere('head_code', 'like', "%{$search}%");
        });
    }
}
