<?php

namespace App\Models;

use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class DocumentTemplate extends Model
{
    use BelongsToTenant, HasFactory, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'name',
        'category',
        'title',
        'company_name',
        'company_address',
        'company_contact',
        'footer_remark_label',
        'footer_judgement_label',
        'footer_judgement_options',
        'is_active',
        'linked_item_ids',
        'linked_process_id',
    ];

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

    /**
     * 결재라인
     */
    public function approvalLines(): HasMany
    {
        return $this->hasMany(DocumentTemplateApprovalLine::class, 'template_id')
            ->orderBy('sort_order');
    }

    /**
     * 기본 필드
     */
    public function basicFields(): HasMany
    {
        return $this->hasMany(DocumentTemplateBasicField::class, 'template_id')
            ->orderBy('sort_order');
    }

    /**
     * 검사 기준서 섹션
     */
    public function sections(): HasMany
    {
        return $this->hasMany(DocumentTemplateSection::class, 'template_id')
            ->orderBy('sort_order');
    }

    /**
     * 테이블 컬럼
     */
    public function columns(): HasMany
    {
        return $this->hasMany(DocumentTemplateColumn::class, 'template_id')
            ->orderBy('sort_order');
    }

    /**
     * 검사 기준서 동적 필드 정의
     */
    public function sectionFields(): HasMany
    {
        return $this->hasMany(DocumentTemplateSectionField::class, 'template_id')
            ->orderBy('sort_order');
    }

    /**
     * 외부 키 매핑 정의
     */
    public function links(): HasMany
    {
        return $this->hasMany(DocumentTemplateLink::class, 'template_id')
            ->orderBy('sort_order');
    }
}
