<?php

namespace App\Models\Tenants;

use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Receiving extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'receiving_number',
        'order_no',
        'order_date',
        'item_id',
        'item_code',
        'item_name',
        'specification',
        'supplier',
        'order_qty',
        'order_unit',
        'due_date',
        'receiving_qty',
        'receiving_date',
        'lot_no',
        'supplier_lot',
        'receiving_location',
        'receiving_manager',
        'status',
        'remark',
        'options',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'order_date' => 'date',
        'due_date' => 'date',
        'receiving_date' => 'date',
        'order_qty' => 'decimal:2',
        'receiving_qty' => 'decimal:2',
        'item_id' => 'integer',
        'options' => 'array',
    ];

    /**
     * JSON 직렬화 시 자동 포함되는 접근자
     */
    protected $appends = [
        'manufacturer',
        'material_no',
        'inspection_status',
        'inspection_date',
        'inspection_result',
    ];

    /**
     * Options 키 상수 (확장 필드)
     */
    public const OPTION_MANUFACTURER = 'manufacturer';          // 제조사

    public const OPTION_MATERIAL_NO = 'material_no';             // 거래처 자재번호

    public const OPTION_INSPECTION_STATUS = 'inspection_status'; // 수입검사 (적/부적/-)

    public const OPTION_INSPECTION_DATE = 'inspection_date';     // 검사일

    public const OPTION_INSPECTION_RESULT = 'inspection_result'; // 검사결과 (합격/불합격)

    /**
     * 상태 목록
     */
    public const STATUSES = [
        'order_completed' => '발주완료',
        'shipping' => '배송중',
        'inspection_pending' => '검사대기',
        'receiving_pending' => '입고대기',
        'completed' => '입고완료',
    ];

    /**
     * 품목 관계
     */
    public function item(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Items\Item::class);
    }

    /**
     * 생성자 관계
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Members\User::class, 'created_by');
    }

    /**
     * 상태 라벨
     */
    public function getStatusLabelAttribute(): string
    {
        return self::STATUSES[$this->status] ?? $this->status;
    }

    /**
     * Options에서 값 가져오기
     */
    public function getOption(string $key, mixed $default = null): mixed
    {
        return $this->options[$key] ?? $default;
    }

    /**
     * Options에 값 설정
     */
    public function setOption(string $key, mixed $value): self
    {
        $options = $this->options ?? [];
        $options[$key] = $value;
        $this->options = $options;

        return $this;
    }

    /**
     * 제조사 접근자
     */
    public function getManufacturerAttribute(): ?string
    {
        return $this->getOption(self::OPTION_MANUFACTURER);
    }

    /**
     * 거래처 자재번호 접근자
     */
    public function getMaterialNoAttribute(): ?string
    {
        return $this->getOption(self::OPTION_MATERIAL_NO);
    }

    /**
     * 수입검사 상태 접근자
     */
    public function getInspectionStatusAttribute(): ?string
    {
        return $this->getOption(self::OPTION_INSPECTION_STATUS);
    }

    /**
     * 검사일 접근자
     */
    public function getInspectionDateAttribute(): ?string
    {
        return $this->getOption(self::OPTION_INSPECTION_DATE);
    }

    /**
     * 검사결과 접근자
     */
    public function getInspectionResultAttribute(): ?string
    {
        return $this->getOption(self::OPTION_INSPECTION_RESULT);
    }

    /**
     * 수정 가능 여부
     */
    public function canEdit(): bool
    {
        return true;
    }

    /**
     * 삭제 가능 여부
     */
    public function canDelete(): bool
    {
        return $this->status !== 'completed';
    }

    /**
     * 입고처리 가능 여부
     */
    public function canProcess(): bool
    {
        return in_array($this->status, ['order_completed', 'shipping', 'inspection_pending', 'receiving_pending']);
    }
}
