<?php

namespace App\Models;

use App\Models\BaseModel;

class ItemLotNumber extends BaseModel
{
    protected $table = 'item_lot_numbers';

    protected $fillable = [
        'company_id','item_id','warehouse_id','lot_number',
        'manufacturing_date','expiry_date',
        'original_qty','remaining_qty',
        'source_voucher_type','source_voucher_id',
    ];

    protected $casts = [
        'manufacturing_date' => 'date',
        'expiry_date'        => 'date',
        'original_qty'       => 'decimal:4',
        'remaining_qty'      => 'decimal:4',
    ];

    public function company()   { return $this->belongsTo(Company::class); }
    public function item()      { return $this->belongsTo(Item::class); }
    public function warehouse() { return $this->belongsTo(Warehouse::class); }

    public function scopeInStock($q)   { return $q->where('remaining_qty', '>', 0); }
    public function scopeByItem($q, int $itemId) { return $q->where('item_id', $itemId); }

    /**
     * FEFO: First Expiry First Out — order lots by expiry date ascending.
     * Used when selecting lots for outward transactions.
     */
    public function scopeFEFO($q)
    {
        return $q->orderBy('expiry_date')->orderBy('id');
    }

    public function isExpired(): bool
    {
        return $this->expiry_date && $this->expiry_date->isPast();
    }

    public function isExpiringSoon(int $days = 30): bool
    {
        return $this->expiry_date &&
               !$this->isExpired() &&
               $this->expiry_date->diffInDays(now()) <= $days;
    }
}
