<?php

namespace App\Models\Items;

use App\Models\Members\User;
use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 품목 입고 모델
 *
 * @property int $id
 * @property int|null $item_id 품목 ID
 * @property int $tenant_id 테넌트 ID
 * @property string $receipt_date 입고일
 * @property string $lot_number LOT번호
 * @property float $received_qty 입고수량
 * @property string $unit 단위
 * @property string|null $supplier_name 공급업체명
 * @property string|null $manufacturer_name 제조업체명
 * @property float|null $purchase_price_excl_vat 매입단가(부가세 제외)
 * @property float|null $weight_kg 중량(kg)
 * @property string $status_code 상태코드
 * @property string $is_inspection 검사여부 (Y/N)
 * @property string|null $inspection_date 검사일
 * @property string|null $remarks 비고
 *
 * @mixin IdeHelperItemReceipt
 */
class ItemReceipt extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $table = 'item_receipts';

    protected $fillable = [
        'item_id',
        'tenant_id',
        'receipt_date',
        'lot_number',
        'received_qty',
        'unit',
        'supplier_name',
        'manufacturer_name',
        'purchase_price_excl_vat',
        'weight_kg',
        'status_code',
        'is_inspection',
        'inspection_date',
        'remarks',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'receipt_date' => 'date',
        'inspection_date' => 'date',
        'received_qty' => 'decimal:2',
        'purchase_price_excl_vat' => 'decimal:2',
        'weight_kg' => 'decimal:2',
    ];

    // ===== Relationships =====

    /**
     * 품목
     */
    public function item()
    {
        return $this->belongsTo(Item::class, 'item_id');
    }

    /**
     * 생성자
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // ===== Scopes =====

    /**
     * 특정 품목의 입고 내역
     */
    public function scopeForItem($query, int $itemId)
    {
        return $query->where('item_id', $itemId);
    }

    /**
     * 특정 일자 이전 입고
     */
    public function scopeBeforeDate($query, string $date)
    {
        return $query->where('receipt_date', '<=', $date);
    }

    /**
     * 단가가 있는 입고만
     */
    public function scopeWithPrice($query)
    {
        return $query->whereNotNull('purchase_price_excl_vat')
            ->where('purchase_price_excl_vat', '>', 0);
    }
}
