<?php

namespace App\Models\Tenants;

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 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',
        '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',
    ];

    /**
     * 상태 목록
     */
    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;
    }

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

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

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