<?php

namespace App\Models;

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

class InventoryTransaction extends Model
{
    use HasFactory;
    use Auditable;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'inventory_id',
        'user_id',
        'transaction_type',  // entry, exit, adjustment, transfer
        'quantity',
        'previous_quantity',
        'new_quantity',
        'reference',
        'reference_id',
        'notes',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'quantity' => 'float',
        'previous_quantity' => 'float',
        'new_quantity' => 'float',
    ];

    /**
     * Get the inventory item for this transaction.
     */
    public function inventory()
    {
        return $this->belongsTo(Inventory::class, 'inventory_id');
    }

    /**
     * Get the user who made this transaction.
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Constants for transaction types
     */
    const TYPE_ENTRY = 'entry';
    const TYPE_EXIT = 'exit';
    const TYPE_ADJUSTMENT = 'adjustment';
    const TYPE_TRANSFER = 'transfer';

    /**
     * Scope a query to only include entries.
     */
    public function scopeEntries($query)
    {
        return $query->where('transaction_type', self::TYPE_ENTRY);
    }

    /**
     * Scope a query to only include exits.
     */
    public function scopeExits($query)
    {
        return $query->where('transaction_type', self::TYPE_EXIT);
    }

    /**
     * Scope a query to only include adjustments.
     */
    public function scopeAdjustments($query)
    {
        return $query->where('transaction_type', self::TYPE_ADJUSTMENT);
    }

    /**
     * Scope a query to only include transfers.
     */
    public function scopeTransfers($query)
    {
        return $query->where('transaction_type', self::TYPE_TRANSFER);
    }
} 