<?php

namespace App\Models\Warehouse;

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

class IncomingItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'incoming_transaction_id',
        'item_id',
        'quantity_received',
        'unit_price',
        'total_price',
        'production_date',
        'expiry_date',
        'batch_number',
        'stock_status'
    ];

    protected $casts = [
        'quantity_received' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'production_date' => 'date',
        'expiry_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($item) {
            // Auto-calculate total price
            $item->total_price = $item->quantity_received * $item->unit_price;
        });
    }

    /**
     * Get the transaction that owns the item
     */
    public function transaction(): BelongsTo
    {
        return $this->belongsTo(IncomingTransaction::class, 'incoming_transaction_id');
    }

    /**
     * Get the item details
     */
    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class);
    }

    /**
     * Check if item is expired
     */
    public function getIsExpiredAttribute()
    {
        return $this->expiry_date && $this->expiry_date < now();
    }

    /**
     * Get days until expiry
     */
    public function getDaysUntilExpiryAttribute()
    {
        if (!$this->expiry_date) {
            return null;
        }

        return now()->diffInDays($this->expiry_date, false);
    }

    /**
     * Get formatted batch number
     */
    public function getFormattedBatchNumberAttribute()
    {
        return $this->batch_number ?: 'N/A';
    }
}