<?php

namespace App\Models\Tenants;

use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class AccountCode extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id',
        'code',
        'name',
        'category',
        'sub_category',
        'parent_code',
        'depth',
        'department_type',
        'description',
        'sort_order',
        'is_active',
    ];

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

    // Categories (대분류)
    public const CATEGORY_ASSET = 'asset';
    public const CATEGORY_LIABILITY = 'liability';
    public const CATEGORY_CAPITAL = 'capital';
    public const CATEGORY_REVENUE = 'revenue';
    public const CATEGORY_EXPENSE = 'expense';

    public const CATEGORIES = [
        self::CATEGORY_ASSET => '자산',
        self::CATEGORY_LIABILITY => '부채',
        self::CATEGORY_CAPITAL => '자본',
        self::CATEGORY_REVENUE => '수익',
        self::CATEGORY_EXPENSE => '비용',
    ];

    // Sub-categories (중분류)
    public const SUB_CATEGORIES = [
        'current_asset' => '유동자산',
        'fixed_asset' => '비유동자산',
        'current_liability' => '유동부채',
        'long_term_liability' => '비유동부채',
        'capital' => '자본',
        'sales_revenue' => '매출',
        'other_revenue' => '영업외수익',
        'cogs' => '매출원가',
        'selling_admin' => '판매비와관리비',
        'other_expense' => '영업외비용',
    ];

    // Department types (부문)
    public const DEPT_COMMON = 'common';
    public const DEPT_MANUFACTURING = 'manufacturing';
    public const DEPT_ADMIN = 'admin';

    public const DEPARTMENT_TYPES = [
        self::DEPT_COMMON => '공통',
        self::DEPT_MANUFACTURING => '제조',
        self::DEPT_ADMIN => '관리',
    ];

    // Depth levels (계층)
    public const DEPTH_MAJOR = 1;
    public const DEPTH_MIDDLE = 2;
    public const DEPTH_MINOR = 3;

    /**
     * 활성 계정과목만 조회
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    /**
     * 소분류(입력 가능 계정)만 조회
     */
    public function scopeSelectable(Builder $query): Builder
    {
        return $query->where('depth', self::DEPTH_MINOR);
    }

    /**
     * 하위 계정과목 관계
     */
    public function children()
    {
        return $this->hasMany(self::class, 'parent_code', 'code')
            ->where('tenant_id', $this->tenant_id);
    }
}
