<?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 GlobalCategory extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'parent_id',
        'code_group',
        'profile_code',
        'code',
        'name',
        'is_active',
        'sort_order',
        'description',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

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

    /**
     * 부모 카테고리
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    /**
     * 자식 카테고리
     */
    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order');
    }

    /**
     * 코드 그룹 스코프
     */
    public function scopeGroup($query, string $group)
    {
        return $query->where('code_group', $group);
    }

    /**
     * 루트 카테고리만 조회
     */
    public function scopeRoot($query)
    {
        return $query->whereNull('parent_id');
    }

    /**
     * 활성 카테고리만 조회
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 계층 깊이를 포함한 이름 반환
     */
    public function getIndentedNameAttribute(): string
    {
        $depth = 0;
        $parent = $this->parent;
        while ($parent) {
            $depth++;
            $parent = $parent->parent;
        }

        return str_repeat('ㄴ ', $depth).$this->name;
    }
}
