<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PurchaseOrderItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'purchase_order_id',
        'product_id',
        'quantity',
        'unit_id', // 新增單位ID欄位
        'unit_price',
        'subtotal',
        'received_quantity',
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'subtotal' => 'decimal:2',
        'received_quantity' => 'decimal:2',
    ];

    public function getProductNameAttribute(): string
    {
        return $this->product?->name ?? '';
    }
    
    // 關聯單位
    public function unit(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Unit::class);
    }

    public function getUnitNameAttribute(): string
    {
        // 優先使用關聯的 unit
        if ($this->unit) {
            return $this->unit->name;
        }

        if (!$this->product) {
            return '';
        }
        
        // Fallback: 嘗試從 Product 的關聯單位獲取
        return $this->product->purchaseUnit?->name 
            ?? $this->product->largeUnit?->name 
            ?? $this->product->baseUnit?->name 
            ?? '';
    }

    public function purchaseOrder(): BelongsTo
    {
        return $this->belongsTo(PurchaseOrder::class);
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }
}
