<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\Auditable;

class Inventory extends Model
{
    use HasFactory, SoftDeletes;
    use Auditable;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'inventory';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'description',
        'category_id',
        'quantity',
        'min_stock',
        'unit_price',
        'expiration_date',
        'location',
        'status',
        'serial_number',
        'brand',
        'model',
        'supplier_id',
        'last_maintenance',
        'next_maintenance',
        'image_path',
        'notes'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'expiration_date' => 'date',
        'last_maintenance' => 'date',
        'next_maintenance' => 'date',
    ];

    /**
     * Get the category that owns the inventory item.
     */
    public function category()
    {
        return $this->belongsTo(InventoryCategory::class, 'category_id');
    }

    /**
     * Get the supplier that owns the inventory item.
     */
    public function supplier()
    {
        return $this->belongsTo(Supplier::class, 'supplier_id');
    }

    /**
     * Get the transactions for the inventory item.
     */
    public function transactions()
    {
        return $this->hasMany(InventoryTransaction::class);
    }

    /**
     * Check if inventory item is low stock.
     */
    public function isLowStock()
    {
        return $this->quantity <= $this->min_stock;
    }

    /**
     * Check if inventory item is out of stock.
     */
    public function isOutOfStock()
    {
        return $this->quantity <= 0;
    }

    /**
     * Check if inventory item is expired or about to expire.
     */
    public function isExpired()
    {
        if (!$this->expiration_date) {
            return false;
        }
        
        return $this->expiration_date->isPast();
    }

    /**
     * Check if inventory item is about to expire (within 30 days).
     */
    public function isAboutToExpire()
    {
        if (!$this->expiration_date) {
            return false;
        }
        
        return $this->expiration_date->diffInDays(now()) <= 30 && !$this->isExpired();
    }

    /**
     * Get all items that require maintenance soon.
     */
    public static function requiresMaintenance()
    {
        return self::whereNotNull('next_maintenance')
            ->whereDate('next_maintenance', '<=', now()->addDays(30))
            ->get();
    }
} 