<?php

namespace App\Models;

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

class LedgGrp extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'ledg_grps';
    protected $primaryKey = 'Gr_Id';
    public $incrementing = true;
    protected $keyType = 'int';
    public $timestamps = false;

    protected $fillable = [
        'Gr_Cd',
        'Up_Gr',
        'Gr_Nm',
        'Gr_Sr',
        'Gr_St',
        'is_del',
        'Gr_Exp',
        'Gr_Buk',
        'Gr_Prt'
    ];

    protected $casts = [
        'Gr_Sr' => 'integer',
        'Gr_St' => 'integer',
    ];

    /* ================= Relationships ================= */

    public function parentGroup()
    {
        return $this->belongsTo(LedgGrp::class, 'Up_Gr', 'Gr_Cd');
    }

    public function childGroups()
    {
        return $this->hasMany(LedgGrp::class, 'Up_Gr', 'Gr_Cd')
                    ->orderBy('Gr_Sr');
    }

    /* ================= Scopes ================= */

    public function scopeActive($query)
    {
        return $query->where('is_del', '!=', 'Y');
    }

    public function scopeLevel($query, $level)
    {
        return $query->where('Gr_St', $level);
    }

    /* ================= Helpers ================= */

    public function isRootLevel(): bool
    {
        return $this->Gr_St === 1;
    }

    public function hasChildren(): bool
    {
        return $this->childGroups()->exists();
    }

    public function getLevelNameAttribute(): string
    {
        return match ($this->Gr_St) {
            1 => 'Root Level',
            2 => 'Level 2',
            3 => 'Level 3',
            4 => 'Level 4',
            default => 'Unknown Level',
        };
    }

    public function getSeriesAttribute(): string
    {
        return substr($this->Gr_Cd, 0, 2);
    }
}
